Document

Python替换文件内容

def replace_contents(old_content, new_content, file_path):
    file_data = ""
    with open(file_path, "r", encoding="UTF-8") as f:
        for line in f:
            if old_content in line:
                line = line.replace(old_content, new_content)
                print("Replace file contents: {0} ——> {1}".format(old_content, new_content), flush=True)
            file_data += line
    f.close()
    with open(file_path, "w", encoding="UTF-8") as f:
        f.write(file_path)
    f.close()
posted @ 2022-02-25 15:38  lsepi  阅读(64)  评论(0编辑  收藏  举报