2016-07-29 47 views
1

我有一個文件,我想選擇文件中的某些行並將其複製到另一個文件。Python:從一個文件中選擇一系列行並將其複製到另一個文件

在第一個文件中,我想要複製的行有單詞「XYZ」,從這裏我想選擇接下來的200行(包括匹配行)並將其複製到另一個文件。下面

是我的代碼

match_1 = 'This is match word' 
with open('myfile.txt') as f1: 
    for num, line in enumerate(f1, 1): 
     if log_1 in line: 
      print line 

上面的代碼使我行的開始,我需要選擇200線形成匹配的行,然後複製,將其移動到另一個文本文件。

我試着像while語句對夫婦的選擇,但我不能夠建立邏輯fully.Please幫助

回答

1

您可以將文件對象使用itertools.islice一旦找到匹配:

from itertools import islice 

# some code before matching line is found 
chunk = line + ''.join(islice(f1, 200)) 

這將消耗迭代器f1到接下來的200行,因此如果循環中放置了循環,則循環中的num計數可能不一致。

如果您不需要在文件中的其他行找到比賽後,你可以使用:

from itertools import islice 

with open('myfile.txt') as f1, open('myotherfile.txt') as f_out: 
    for num, line in enumerate(f1, 1): 
     if log_1 in line: 
      break 
    chunk = line + ''.join(islice(f1, 200)) 
    f_out.write(chunk) 
+0

感謝摩西爲您的快速響應。這完全解決了我的問題。 – Davidson

0

如何像

>>> with open("pokemonhunt", "r") as f: 
... Lines = [] 
... numlines = 5 
... count = -1 
... for line in f: 
...  if "pokemon" in line:   % gotta catch 'em all!!! 
...  count = 0 
...  if -1 < count < numlines: 
...  Lines.append(line) 
...  count += count 
...  if count == numlines: 
...  with open("pokebox","w") as tmp: tmp.write("".join(Lines)) 

還是我誤解你的問題?

+0

(顯然,如果你期望多個匹配,每次改變outfile名稱,或追加到相同的文件等) –

+0

感謝Tasos爲您的快速反應....實際上我想打開一個文件並搜索一旦我得到了匹配,我需要複製下200行,並在一個新的文件進行進一步分析。我會嘗試添加更清晰的下一次我的問題... – Davidson

+0

是的,這是什麼這是。 (如果你的話是「口袋妖怪」,你想要5行:p) –

相關問題