defalter(file,old_str,new_str): """ 替换文件中的字符串 :param file:文件路径 :param old_str:旧字符串 :param new_str:新字符串 :return: """ file_data = "" withopen(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 withopen(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")