2017-03-03 27 views
0

我有一個文本文件foo.txt的,看起來像寫回同一個文件:找到一個模式,編輯下一行,並使用python

I dont care! 
pattern and stuff 
this line : to_edit 
this line : no_edit 
some other lines 
this line : to_edit 
pattern and stuff 
another line : to_edit 
another line : to_edit 

我想找到模式和編輯只剩下一行沒有其他線路並寫回到同一foo.txt的像這樣:

I dont care! 
pattern and stuff 
this line : EDITED 
this line : no_edit 
some other lines 
this line : to_edit 
pattern and stuff 
another line : EDITED 
another line : to_edit 

我也不想用f.readline()和f.seek()我到目前爲止,看起來像這樣的代碼:

import re 
from tempfile import mkstemp 
from shutil import move 
from os import remove, close 
def replace(foo.txt): 
    searchPattern = re.compile("^pattern") 
    pattern = "to_edit" 
    subst = "EDITED" 
    fh, abs_path = mkstemp() 
    nextLine = 0 
    with open(abs_path,'w') as new_file: 
     with open(file_path) as old_file: 
      for line in old_file: 
       if nextLine == 0: 
        if searchPattern.search(line): 
         nextLine = 1 
         continue 
        else: 
         new_file.write(line) 
       else: 
        new_file.write(re.sub(pattern,subst,line)) 
        nextLine = 0 
    close(fh) 
    remove(foo.txt) 
    move(abs_path, foo.txt) 

我愛上這個編碼是一種非常低效的方式和獲得解決方案。

+0

你可以把一切都變成了正則表達式,但我認爲這可能是*比當前解決方案效率較低,所以你可以忽略這條評論... – Max

回答

1

看來,你的代碼是缺少一些東西(如searchPattern是一個字符串,而不是具有search屬性),但你可以使用next()獲得從文件迭代器的下一行,當你發現搜索模式。

從您的代碼適應:

def replace(foo.txt): 
    searchPattern = re.compile("^pattern") 
    pattern = "to_edit" 
    subst = "EDITED" 
    fh, abs_path = mkstemp() 
    with open(abs_path,'w') as new_file: 
     with open(file_path) as old_file: 
      for line in old_file: 
       # As it is, this next line should not work, but assuming that it returns True when the pattern is found.. 
       if searchPattern.search(line): 
        # Write current line 
        new_file.write(line) 
        # Get next line 
        next_line = next(old_file) 
        # Write edited line 
        new_file.write(re.sub(pattern,subst,next_line)) 
       else: 
        new_file.write(line) 
+0

我糾正該代碼我忘了添加re.compile()搜索模式,這就是爲什麼它拋出了錯誤。用你的代碼不會把它編寫成兩行,而用to_edit寫兩行?如果我錯了,請糾正我的錯誤 –

+0

當您在'old_file'迭代器上使用next()時,它會將下一行檢索(並耗盡)到next_line變量中。這意味着在'old_file'循環中'for line'的下一次迭代中,'line'變量將成爲to_edit行之後的行。 – ODiogoSilva

相關問題