Python 2.7 如何使用python从文本文件中读取单独的行

Python 2.7 如何使用python从文本文件中读取单独的行,python-2.7,Python 2.7,这是我的示例代码,用于编写一行文字为“util.exe”的代码。但我需要阅读“util.exe”行下面的一行 例如,我有一个包含这些行的文本文件 with open("file.txt") as f: lines = f.readlines() lines = [l for l in lines if "util.exe" in l] with open("Lines.txt", "w") as f1: new=f1.writelines(lines) pcm wav线

这是我的示例代码,用于编写一行文字为“util.exe”的代码。但我需要阅读“util.exe”行下面的一行

例如,我有一个包含这些行的文本文件

with open("file.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "util.exe" in l]
with open("Lines.txt", "w") as f1:
    new=f1.writelines(lines)
pcm wav线路我需要读取

这里我需要读取一行
pcm wav行,我需要读取
下面的
util.exe行中的


请您为我提供指导。

这里是一个建议的解决方案。只需通过枚举行,然后访问util.exe后的行来修改您的列表理解。下面是修改代码:

1/16 joc_... 

cd D:\cmd\find\joc

util.exe line
destLines = []
with open("file.txt") as fp:
   lines = fp.readlines()
   index = 0
   for line in lines:
      index += 1
      if 'exe' in line and len(lines) >= index:
          destLines.append(lines[index])

with open("lines.txt", "w") as fp:
     fp.writelines(destLines)
因此,当我运行修改后的脚本时,结果如下: 示例内容

“file.txt”->

这是输出文件“Lines.txt”:


事实上,我需要读一行在“exe”下面的内容。那是在第行下面。很抱歉迟到了…谢谢。这很好
with open("file.txt") as f:
    lines = f.readlines()
    lines = [lines[index + 1] for index, l in enumerate(lines) if "util.exe" in l]
with open("Lines.txt", "w") as f1:
    new=f1.writelines(lines)
this is a test line
and here is another one
util.exe is here
this one should be recorded
but this one should not
now it appears at the end util.exe
this should also be saved. finally,
another case
the test phrase util.exe is in the middle
where this should be saved
but not this one
this one should be recorded
this should also be saved. finally,
where this should be saved