首先,我的示例文本文件的内容如下所示:
Some Data
Nothing important
Start here
This is important
Grab this line too
And this ono too
End here
Text goes on, but isn't important
Next text
Blaah
现在,我想读取文本文件,并且只想抓取“从这里开始”和“从这里结束”之间的行。
所以我的 Python 代码如下所示:
filename = 'example_file.txt'
with open(filename, 'r') as input:
for line in input: # First loop breaks at specific line
if 'Start here' in line:
break
for line_1 in input: # Second loop grabs all lines
print line_1.strip()
for line_2 in input: # Third loop breaks at specific line
if 'End here' in line_2:
break
但是这不起作用。
这是我运行时的输出:
This is important
Grab this line too
And this on too
End here
Text goes on, but isn't important
Next text
Blaah
如您所见,我的脚本不会在此处结束处中断。程序从正确的行开始,但不会在正确的行处中断。
出了什么问题?
最佳答案
这是需要中断的第二个循环...
for line_1 in input:
if 'End here' in line_1:
break
print line_1.strip()
关于python - 读取文本文件中的行间内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38379423/