1

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.

1 Answer 1

2

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}')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Sam. One modification. Instead of [1], [-1] showing the date but it works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.