字符串匹配Python后替换行

时间:2016-04-27 16:46:38

标签: python

所以我有一个包含行"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')

0 个答案:

没有答案