Python 批量修改或替换文本内容

Python 批量修改或替换文本内容

前言

遇到一个需要将一堆代码中部分文字替换或删除的需求。
需要处理像下面上百个脚本
想要处理的文件堆
需要删除每个脚本中类似下图的内容
需要删除的内容
可以用python批量处理所有的代码,并且删除我想要删除的内容。

源码

其中使用chardet来处理不同字符集的问题,因为不同操作系统保存的文件字符编码或许不同。

import os
import chardet

def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        raw_data = f.read()
        result = chardet.detect(raw_data)
        return result['encoding']

def traverse_folder(folder_path,original_str,new_str):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".cs"):
                file_path = os.path.join(root, file)
                print(f"File: {
      
      file_path}")
                # 检测文件编码
                file_encoding = detect_encoding(file_path)
                print(f"Encoding: {
      
      file_encoding}")

                with open(file_path, "r+", encoding=file_encoding, errors='ignore') as f:
                    content = f.read()
                    # 替换字符串
                    replaced_content = content.replace(original_str, new_str)
                    # print(replaced_content)
                    # 将替换后的内容写入原始文件
                    f.seek(0)
                    f.write(replaced_content)
                    f.truncate()
                    print("File modified.")
                print("-" * 50)


# 注意:如果你在 Windows 系统上使用反斜杠作为文件夹路径分隔符,请将反斜杠转义或者使用原始字符串(在路径字符串前面加上 r),
# 例如 "C:\\path\\to\\your\\folder" 或 r"C:\path\to\your\folder"。
# 在其他操作系统上(如 Linux 或 macOS),可以使用正斜杠作为路径分隔符,
# 例如 "/path/to/your/folder"。

# 指定文件夹路径
folder_path = r"D:\Project\Python\DelMLineString\Code"
# 要替换的字符串
original_str = '''
    /// <summary>
    /// buff进入
    /// </summary>
    /// <param name="bfrls"></param>
    /// <param name="role"></param>
    /// <param name="enemy"></param>
    /// <param name="json"></param>
    public override void BuffOnEnter(RoleAttribute self, RoleAttribute other, string json)
    {
        m_Entity = JsonUtility.FromJson<BuffEntityBase>(json);
        base.BuffOnEnter(self, other, json);
        m_buffInfo = m_Entity;
        InitAttr();
    }'''

#新的字符串
new_str = '''
'''
# 调用函数遍历文件夹
traverse_folder(folder_path,original_str,new_str)

效果图

顺利删除所有脚本中需要删除的内容,替换也一样。
效果图

鸣谢

ChatGPT

猜你喜欢

转载自blog.csdn.net/a71468293a/article/details/131539887
今日推荐