Use python script to modify the contents of files in a large number of folders

Note that this script can only replace one content at a time

Traversing files reference: (11 messages) How to traverse all files in a folder and its subfolders in python (with implementation code)_C Xiao C’s Blog-CSDN Blog_python Traverse the files in all subfolders of the directory and divide them into two kind


import os
import re
import sys

# 遍历文件夹下的所有需要修改的文件
def get_filelist(dir, Filelist):
    newDir = dir

    if os.path.isfile(dir):

        Filelist.append(dir)

        # # 若只是要返回文件文,使用这个

        # Filelist.append(os.path.basename(dir))

    elif os.path.isdir(dir):

        for s in os.listdir(dir):
            # 如果需要忽略某些文件夹,使用以下代码

            # if s == "xxx":

            # continue

            newDir = os.path.join(dir, s)

            get_filelist(newDir, Filelist)

    return Filelist

mark_url = input('请输入文件所在的文件夹地址:')
modify_it = input('请输入被修改的部分:')
want_it = input('请输入你想修改成的内容:')
par = re.compile(modify_it)
modify_list = []  # 可修改文件名的列表
# file_list = os.listdir(mark_url)  # 待修改文件夹
file_list = get_filelist(mark_url, [])
print("修改前:\n" + str(file_list))  # 输出文件夹中包含的文件
current_path = os.getcwd()  # 得到进程当前工作目录
os.chdir(mark_url)  # 将当前工作目录修改为待修改文件夹的位置

for filename in file_list:
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read()
    with open(filename, 'w', encoding='utf-8') as f:
        # 查看文件是否相匹配
        if modify_it in content:
            modify_list.append(filename)
            # 替换文件内容
            file = par.sub(want_it, content)
            f.write(file)
        else:
            # 不替换文件内容
            f.write(content)
            print('所要修改的内容源文件里面没有!!!')

if modify_list:
    print('可修改的文件名为:\n', modify_list)
    print('修改完毕!')
else:
    print('没有可以修改的文件!')

os.chdir(current_path)  # 改回程序运行前的工作目录
sys.stdin.flush()  # 刷新

Guess you like

Origin blog.csdn.net/qq_42019881/article/details/127829880