[英]python parse conditional multiple lines in text file
我想解析一個文本文件,但有多個條件:
輸入:
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
任務:我需要在位置之前找到“位置:x --> y”和日期。 txt 文件可以包含未知數量的位置更改。
所需輸出:
2019/12/10 10:40:23, location: A --> B
2020/01/17 11:11:59, location: E --> F
我嘗試了一些代碼,例如:
with open('log.txt', 'r') as searchfile:
for line in searchfile:
if 'location' in line:
print (line)
但只能找到位置,我不知道如何找到它們的日期。
先感謝您。
只需跟蹤相應的時間和地點:
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}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.