我无法让python读取特定的行。我正在做的是这样的事情:
lines of data not needed
lines of data not needed
lines of data not needed
--------------------------------------
***** REPORT 1 *****
--------------------------------------
[key] lines of interest are here
[key] lines of interest are here
[key] lines of interest are here
[key] lines of interest are here
[key] lines of interest are here #This can also be the EOF
--------------------------------------
***** REPORT 2 *****
--------------------------------------
lines of data not needed
lines of data not needed
lines of data not needed #Or this will be the EOF
我尝试的是:
flist = open("filename.txt").readlines()
for line in flist:
if line.startswith("\t**** Report 1"):
break
for line in flist:
if line.startswith("\t**** Report 2"):
break
if line.startswith("[key]"):
#do stuff with data
但是,当文件以没有结束分隔符结束时出现问题...例如,当没有显示报告#2时。什么是更好的方法?
答案 0 :(得分:6)
一个看起来应该覆盖你的问题的轻微修改:
flist = open("filename.txt").readlines()
parsing = False
for line in flist:
if line.startswith("\t**** Report 1"):
parsing = True
elif line.startswith("\t**** Report 2"):
parsing = False
if parsing:
#Do stuff with data
如果你想避免解析“ * 报告1”......本身,只需将开始条件放在if parsing
之后,即
flist = open("filename.txt").readlines()
parsing = False
for line in flist:
if line.startswith("\t**** Report 2"):
parsing = False
if parsing:
#Do stuff with data
if line.startswith("\t**** Report 1"):
parsing = True
答案 1 :(得分:0)
在这里可以使用itertools模块替代。
尽管这里的问题需要检查[key],但我还要添加itertool.islice(),以表明当用户有一些先入之先时,可以在开始阅读标记之后跳过几行信息。
from itertools import takewhile, islice, dropwhile
with open('filename.txt') as fid:
for l in takewhile(lambda x: '***** REPORT 2 *****' not in x, islice(dropwhile(lambda x: '***** REPORT 1 *****' not in x, fid), 1, None)):
if not '[key]' in l:
continue
print(l)