所以我有一个包含行"log_path=/etc/log/log-XXXXX-YY-ZZ"
的文件,我想用"log_path=/etc/log/log-*random-generated*"
我尝试使用我在其他主题中找到的以下代码,但这似乎只是用log_path
覆盖log_path=new
部分,因此最终结果为log_path=new=/etc/log/log-XXXX-YY-ZZ
我一直在努力解决这个问题。你能帮我吗?
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace(file_path, subst):
#Create temp file
fh, abs_path = mkstemp()
with open(abs_path,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace('log_path', subst))
close(fh)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
replace('/etc/file/here','log_path=new')