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)
它做我想要什么,但我想知道是否有写代码的任何其他有效的方法。我来自嵌入式背景,所以我正在使用标志如在我的代码中搜索。
谢谢!
感谢您的建议。但我不想替换整个文件,我想只在开始和结束之间替换该行 –