Reputation: 121
I would like to parse a text file, but with multiple conditions:
Input:
something<br />
something <br />
something<br />
Modifications made by xy (xy) on 2019/12/10 10:40:23<br />
location: A --> B<br />
something<br />
something<br />
something<br />
Modifications made by xz (xz) on 2020/01/17 11:11:59<br />
analyzer: C --> D<br />
analyzer: B --> D<br />
analyzer: G --> D<br />
location: E --> F<br />
something<br />
something<br />
something
Task: I need to find the "location: x --> y" and date before the location. The txt file can contains unknown number of location change.
Required Output:
2019/12/10 10:40:23, location: A --> B
2020/01/17 11:11:59, location: E --> F
I tried some code eg.:
with open('log.txt', 'r') as searchfile:
for line in searchfile:
if 'location' in line:
print (line)
but only find the locations and I don't know how to find the dates for them.
Thank you in advance.
Upvotes: 1
Views: 446
Reputation: 2321
Just keep track of corresponding times and locations as such:
with open('log.txt', 'r') as searchfile:
time = None
for line in searchfile:
if line.startswith('Modifications made by'):
time = line.split('on')[-1].strip()
elif line.startswith('location') and time is not None:
print(f'{time}, {line}')
Upvotes: 2