python - 读取文本文件中的行间内容

标签 python

首先,我的示例文本文件的内容如下所示:

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/

相关文章:

python - 如何返回标签的原始值

Python包从外部调用时无法导入邻居子包

python - 如何获得 Python 中的默认文件权限?

python - 如何在多重继承中使用命名元组

python - 如何检查我的一列值是否存在于另一列中

python - 使用 python/psycopg2 循环遍历 PostgreSQL 表时发出 w/UPDATE

python - 在 CustomLabelModelChoiceField 中使用 context_processors 变量

python - Django 应用程序未在 Elastic Beanstalk AWS 上启动

python - 具有共享队列和结束条件的多处理

Python:如何找到使levenshtein距离的字符的位置