Python替换文件内容函数

Python替换文本的简易函数

  • 一行一行替换

    import os
    def fun(path,old_content,new_content):
        with open(path,encoding='utf-8') as f1,\
            open('test',encoding='utf-8',mode='w') as f2:
            for line in f1:
                new_line = line.replace(old_content,new_content)
                f2.write(new_line)
        os.remove(path)
        os.renames('test',path)
    

posted on 2020-06-06 19:04  Ajin0427  阅读(166)  评论(0)    收藏  举报

导航