Python替换文件夹下所有脚本中包含某行字符串的数据

需求背景:

因为业务原因,脚本中的事务名称需要全部删除,替换成空字符串,但是仅仅只能删除我们业务端开启的事务名称,平台端的事务名称不能删除。

众所周知,平台不会动,你也动不了,所以需要写个脚本统一处理下当前已经存在的几百个脚本。

内容分析:

如下图,脚本中事务的名称如下:

删除事务名称后,理论上的结果如下:

JrnRes.CompareExpectedResult("事务数据", "成功提交用户事务:", "Text");

实现分析:

1、搜索当前文件目录下的所有文件

    current_dir = os.getcwd()  # 获取当前目录
    total_replacements = 0
    processed_files = 0
    
    print(f"开始搜索目录: {current_dir}")
    
    # 递归遍历所有子目录
    for root, dirs, files in os.walk(current_dir):
        for file in files:
            # 检查文件扩展名

这里为什么是两层for循环呢?

要从脚本的目录结构说起,因为脚本放在一个大文件夹下,一个脚本就是一个单独的小文件夹,小文件夹中才是具体脚本内容和资源文件。因此需要双层循环来查找。

又因为脚本都是 js 文件,所以接下来会过滤 js 文件。

2、读取单个文件,按关键字替换内容

因为每个事物都有关键字“成功提交用户事务”,因此用这个关键字作为过滤,替换对应数据

def process_file(file_path, search_string, replacement_line):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        
        new_lines = []
        replacements = 0

        for line in lines:
            if search_string in line:
                new_lines.append(replacement_line + '\n')
                replacements += 1
                print(f"在 {file_path} 中替换: {line.strip()} -> {replacement_line}")
            else:
                new_lines.append(line)
        
        if replacements > 0:
            with open(file_path, 'w', encoding='utf-8') as file:
                file.writelines(new_lines)
            print(f"已更新文件: {file_path}")
        
        return replacements
        
    except Exception as e:
        return 0

3、最后需要过滤一些不用替换的内容

def process_file(file_path, search_string, replacement_line):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        
        new_lines = []
        replacements = 0

        skip_strs = ["打开文档", "加载链接文档", "初始化文档", "设置视图比例", "大坐标平移", "绘制多段线区域边界", "创建预设参数对象", "删除 elements", "移动", "save layer info", "修改构件属性"]

        for line in lines:
            need_continue = False
            for skip_str in skip_strs:
                if skip_str in line:
                    need_continue = True
            if need_continue:
                new_lines.append(line)
                continue
            if search_string in line:
                new_lines.append(replacement_line + '\n')
                replacements += 1
                print(f"在 {file_path} 中替换: {line.strip()} -> {replacement_line}")
            else:
                new_lines.append(line)
        
        if replacements > 0:
            with open(file_path, 'w', encoding='utf-8') as file:
                file.writelines(new_lines)
            print(f"已更新文件: {file_path}")
        
        return replacements
        
    except Exception as e:
        return 0

最后,整合一下代码

import os

def replace_lines_in_all_subfolders(search_string, replacement_line, file_extensions=None):
    """
    递归搜索当前目录下所有子文件夹,替换包含特定字符串的整行
    
    参数:
        search_string: 要搜索的字符串
        replacement_line: 替换后的整行内容
        file_extensions: 要处理的文件扩展名列表,如 ['.txt', '.log'],如果为None则处理所有文件
    """
    current_dir = os.getcwd()  # 获取当前目录
    total_replacements = 0
    processed_files = 0
    
    print(f"开始搜索目录: {current_dir}")
    
    # 递归遍历所有子目录
    for root, dirs, files in os.walk(current_dir):
        for file in files:
            # 检查文件扩展名
            if file_extensions:
                file_ext = os.path.splitext(file)[1].lower()
                if file_ext not in [ext.lower() for ext in file_extensions]:
                    continue
            print(f"正在处理文件 {file}......")
            file_path = os.path.join(root, file)
            replacements = process_file(file_path, search_string, replacement_line)
            
            if replacements > 0:
                processed_files += 1
                total_replacements += replacements
    
    print(f"\n完成! 在 {processed_files} 个文件中进行了 {total_replacements} 处行替换")

def process_file(file_path, search_string, replacement_line):
    """
    处理单个文件,替换包含搜索字符串的行
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        
        new_lines = []
        replacements = 0

        skip_strs = ["打开文档", "加载链接文档", "初始化文档", "设置视图比例", "大坐标平移", "绘制多段线区域边界", "创建预设参数对象", "删除 elements", "移动", "save layer info", "修改构件属性"]

        for line in lines:
            need_continue = False
            for skip_str in skip_strs:
                if skip_str in line:
                    need_continue = True
            if need_continue:
                new_lines.append(line)
                continue
            if search_string in line:
                new_lines.append(replacement_line + '\n')
                replacements += 1
                print(f"在 {file_path} 中替换: {line.strip()} -> {replacement_line}")
            else:
                new_lines.append(line)
        
        if replacements > 0:
            with open(file_path, 'w', encoding='utf-8') as file:
                file.writelines(new_lines)
            print(f"已更新文件: {file_path}")
        
        return replacements
        
    except Exception as e:
        # 忽略无法读取的文件(如二进制文件)
        return 0

# 使用示例
if __name__ == "__main__":
    # 替换所有子文件夹中.js文件里包含"错误"的行
    replace_lines_in_all_subfolders(
        search_string="成功提交用户事务",
        replacement_line="JrnRes.CompareExpectedResult(\"事务数据\", \"成功提交用户事务:\", \"Text\");",
        file_extensions=['.js']
    )
    input()

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值