05_Other-Using the Python open function to batch replace file content

Updated on 2023/02/06#

VSCode has integrated the function of "batch replacing specified content in files under a certain path", which is more convenient.


1. Introduction#

After jsd became invalid, the author used a new image hosting solution and needs to replace the original jsd image links in the articles with the new image addresses.

There are many scripts available online for this purpose, and they are highly recommended, such as:

2. Script Content#

Source code from: Batch modify file content (Python version)

The script uses a recursive approach to traverse all files under the directory specified in lines 43 to 46, and performs batch replacement.


  1. Modify the directories to be traversed in lines 43 to 46 according to your own situation; modify the content to be replaced in lines 47 and 48.
  2. Line 24 of the script limits the modification to Markdown files only. If you need to modify other types of text files, you need to change the file extension for matching.
  3. Please backup the source files before executing the script in case you cannot restore them if something goes wrong.
# -*- coding: UTF-8 -*-

# Source code reference:

import os
import re

# File search: find . -name file_name -type f
# Search function: search_path is the root path for searching

# Get the path of the articles
def search(search_path, search_result):
    # Get all files in the current path
    all_file = os.listdir(search_path)
    # For each file
    for each_file in all_file:
        # If the file is a directory
        if os.path.isdir(search_path + each_file):
            # Recursively search
            search(search_path + each_file + '/', search_result)
        # If it is the file to be searched
            if re.findall('.*\.md$', each_file) == [each_file]:
            # Output the path
                search_result.append(search_path + each_file)

# Replace: sed -i 's/old_str/new_str/'
# replace_file_name is the file path to be replaced, replace_old_str is the string to be replaced, replace_new_str is the replacement string
def replace(replace_file_name, replace_old_str, replace_new_str):
    with open(replace_file_name, "r", encoding = "UTF-8") as f1: 
        content =
        t = content.replace(replace_old_str, replace_new_str)
    with open(replace_file_name, "w", encoding = "UTF-8") as f2:

# Places to be modified
#path = 'E:/code_zone/.history/20220831_blog/source/_posts/'
path_list = [
old_str = ''
new_str = ''

search_result = []

if __name__ == '__main__':
    result = []                 # Store file paths
    # Default: current directory
    # path = os.getcwd()
    for path in path_list:
        search(path, result)    # Get the path of the articles
    count = 0
    for file_name in result:
        replace(file_name, old_str, new_str)
        count += 1
        print("{} done  {}".format(file_name, count))

# Command
# python E:/code_zone/tools/python-replace/

3. Reference Articles#

Source code from: Batch modify file content (Python version)

Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.