【发布时间】:2017-07-23 23:37:29
【问题描述】:
我有一个文本文件 foo.txt,它看起来像:
first 01
start
some thing 01
and more 101
i dont care
end
i dont care
final 01
我想将 start 和 行之间的所有 01 替换为 10像这样在同一个 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)
它可以满足我的需求,但我想知道是否有其他有效的方法来编写代码。我来自嵌入式背景,所以我在我的代码中使用了 flag,例如 search。
谢谢!
【问题讨论】:
标签: python-3.x file search replace