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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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")