Python读取两个字符串之间的特定行文本
问题描述:
我无法通过python读取特定行。什么我的工作是这样的: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未显示时。什么是更好的方法?
答
一个轻微的修正,它看起来像它应该包括你的问题:
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
我喜欢它:)我会试试这个,明天 – user1443368 2012-07-31 02:56:39
或者,你可以把一个'continue'语句解析= TRUE;后'不解析“\ * \ * \ *报告1 \ * \ * \ * \ *'行。 – mgilson 2012-07-31 03:00:00
@mgilson:虽然我同意继续循环效率低下......为什么你建议'continue'而不是'break'? – jmetz 2016-03-20 15:36:57