Python batch modify or replace text content

Python batch modify or replace text content

foreword

Encountered a need to replace or delete some text in a bunch of codes.
Need to process hundreds of scripts like the ones below.
pile of files to process
Need to delete the content in each script similar to the picture below. You
What needs to be removed
can use python to process all the codes in batches and delete the content I want to delete.

source code

Among them, chardet is used to deal with the problem of different character sets, because the character encodings of files saved in different operating systems may be different.

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)

renderings

Successfully delete all the content that needs to be deleted in the script, and the replacement is the same.
renderings

thank you

ChatGPT

Supongo que te gusta

Origin blog.csdn.net/a71468293a/article/details/131539887
Recomendado
Clasificación