Python读取两个字符串之间的特定文本行

use*_*368 4 python text readlines

我无法让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
Run Code Online (Sandbox Code Playgroud)

我尝试过的是:

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
Run Code Online (Sandbox Code Playgroud)

但是,当文件结束而没有结束分隔符时,我遇到问题...例如,当没有显示报告#2时.什么是更好的方法?

jme*_*etz 8

一个略微修改看起来应该涵盖你的问题:

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 
Run Code Online (Sandbox Code Playgroud)

如果你想避免解析行" * Report 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
Run Code Online (Sandbox Code Playgroud)

  • 或者,你可以在`parsing = True`之后放一个`continue`语句来解析'\*\*\*Report 1\*\*\*\*'行. (3认同)