Python脚本之对目录下所有文件进行字符串替换

  大Null在对自己的个人网站博客做迁移时,有很多批量性的重复操作,人工去修改的话很是费事,所以写了个小脚本方便 blog 批量修改,这里记录一下:

import os

def alter(file,old_str,new_str):
    """
    替换文件中的字符串
    :param file:文件路径
    :param old_str:旧字符串
    :param new_str:新字符串
    :return:
    """
    file_data = ""
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data += line
    with open(file,"w",encoding="utf-8") as f:
        f.write(file_data)

if __name__ == '__main__':
    # 目录路径
    path = 'C://blog//source//_posts'
    for file_name in os.listdir(path):
        alter(path + "//" + file_name, "old_str", "new_str")

你可能感兴趣的:(Python,python)