mycpen

Mycpen

记录学习历程与受益知识
github
telegram
bilibili

05_Other-使用 Python open 函数批量替换文件内容

2023/02/06 更新#

VSCode 集成了 某路径下的文件批量替换指定内容 的功能,更方便

image-20230206183933193

1. 前言#

jsd 失效之后,博主使用了新的图床方案,需将文章的原 jsd 图片链接替换为新的图片地址

这类脚本在网上有很多,都很推荐,如

2. 脚本内容#

源码来自:批量修改文件内容(Python 版)

脚本采用递归的方式,遍历 43~46 行 目录下的所有文件,进行批量替换

说明:

  1. 根据自身情况修改 43~46 行 需遍历的目录;修改 47、48 行 需要替换的内容
  2. 脚本第 24 行 限制了只筛选出 Markdown 类型的文本文件进行修改,如需修改其他类型的文本文件 需自行更改后缀进行匹配
  3. 执行前请先备份源文件,以防出错后无法还原
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 源码参考  https://blog.csdn.net/qq_38150250/article/details/118026219

import os
import re

# 文件查找 find . -name file_name -type f
# 查找函数:search_path 查找根路径 

# 获取文章路径
def search(search_path, search_result):
    # 获取当前路径下地所有文件
    all_file = os.listdir(search_path)
    # 对于每一个文件
    for each_file in all_file:
        # 若文件为一个文件夹
        if os.path.isdir(search_path + each_file):
            # 递归查找
            search(search_path + each_file + '/', search_result)
        # 如果是需要被查找的文件
        else:
            if re.findall('.*\.md$', each_file) == [each_file]:
            # 输出路径
                search_result.append(search_path + each_file)


# 替换 sed -i 's/old_str/new_str/'
# 文本替换 replace_file_name 需要替换的文件路径,replace_old_str 要替换的字符,replace_new_str 替换的字符
def replace(replace_file_name, replace_old_str, replace_new_str):
    with open(replace_file_name, "r", encoding = "UTF-8") as f1: 
        content = f1.read()
        f1.close()
        t = content.replace(replace_old_str, replace_new_str)
    with open(replace_file_name, "w", encoding = "UTF-8") as f2:
        f2.write(t)
    f2.close()


# 需要改的地方
#path = 'E:/code_zone/.history/20220831_blog/source/_posts/'
path_list = [
    'E:/code_zone/hexo-source/source/_posts/',
    'E:/code_zone/hexo-source-butterfly/source/_posts/',
]
old_str = 'https://image.cpen.top/image/'
new_str = 'https://image.cpen.top/image/'

search_result = []

if __name__ == '__main__':
    result = []                 # 存放文件路径
    # 默认当前目录
    # path = os.getcwd()
    for path in path_list:
        search(path, result)    # 获取文章路径
    count = 0
    for file_name in result:
        replace(file_name, old_str, new_str)
        count += 1
        print("{} done  {}".format(file_name, count))

# 命令
# python E:/code_zone/tools/python-replace/replace.py

3. 参考文章#

源码来自:批量修改文件内容(Python 版)

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。