1
在一個文件中的行文本我有一個文本文件foo.txt的,看起來像:如何更新一行
first 01
start
some thing 01
and more 101
i dont care
end
i dont care
final 01
我想與全部更換線路之間啓動和末在同一foo.txt的,像這樣:
first 01
start
some thing 10
and more 110
i dont care
end
i dont care
final 01
我到目前爲止的代碼看起來像:
import re
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace(foo.txt):
searchStart = re.compile("^start")
searchEnd = re.compile("^end")
pattern = "01"
subst = "10"
fh, abs_path = mkstemp()
search = 0
with open(abs_path,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
if searchEnd.search(line):
search = 0
elif searchStart.search(line):
search = 1
if search == 1:
new_file.write(re.sub(pattern,subst,line))
else:
new_file.write(line)
close(fh)
remove(foo.txt)
move(abs_path, foo.txt)
它做我想要什麼,但我想知道是否有寫代碼的任何其他有效的方法。我來自嵌入式背景,所以我正在使用標誌如在我的代碼中搜索。
謝謝!
感謝您的建議。但我不想替換整個文件,我想只在開始和結束之間替換該行 –