我有一個文本文件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)
我愛上這個編碼是一種非常低效的方式和獲得解決方案。
你可以把一切都變成了正則表達式,但我認爲這可能是*比當前解決方案效率較低,所以你可以忽略這條評論... – Max