如何使用python

时间:2016-09-01 04:28:41

标签: python-2.7

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)

这是我编写一行文本“util.exe”的示例代码。但是我需要在“”util.exe“行中读取一行。

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

1/16 joc_... 

cd D:\cmd\find\joc

util.exe line

pcm wav line我需要阅读

在这里,我需要阅读pcm wav line i need to read

下面的一行util.exe line

请你指导我。

2 个答案:

答案 0 :(得分:1)

Here is a suggested solution. Just modify your list comprehension by enumerating the lines and then accessing the line after the util.exe. So here is modified code:

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)

So when I run the modified script here are the results: Contents of example

"file.txt" -->

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 is the output file "Lines.txt":

this one should be recorded
this should also be saved. finally,
where this should be saved

答案 1 :(得分:0)

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)