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

标签 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

我尝试过的是这样的:

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 

如果您想避免解析行“* 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

关于Python读取两个字符串之间的特定文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11732383/

相关文章:

r - 从文本中提取数据的最有效方法

Powershell - 如何从文本文件中获取前几行?

python - 在 python 中编程时钟时,如何允许用户输入自己的当前时间值?

python - 使用线性回归处理缺失值

python - Django Rest Framework View 返回一个空对象

python - 如何获取一列中所有唯一的值组合,这些值在另一列中

performance - 文本编辑器内部文本存储: optimal chunk size?

python - 删除Python中每个元素的换行符

Python - 将 .readlines() 与 .rstrip() 结合使用,然后将所有单词存储到列表中

python - 如何避免在 Python 文件输入库中缓冲