obsidian/笔记文件/2.笔记/python批量添加宏.md
2025-03-26 00:02:56 +08:00

1.4 KiB
Raw Permalink Blame History

#unity/日常积累 #python

UnityHong.py

这里是批量添加 #if UNITY_IOS 相关的宏

import os
import re

def process_cs_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    
    # Add #if UNITY_IOS at the beginning and #endif at the end
    new_content = f"#if UNITY_IOS\n{content}\n#endif"
    new_content = re.sub(r'\ufeff', '', new_content)
    
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(new_content)
    print(f"Processed {file_path}")

def traverse_folder_and_process_cs_files(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.cs'):
                cs_file_path = os.path.join(root, file)
                process_cs_file(cs_file_path)

# Specify the path to the folder you want to traverse
folder_path = 'C:/Users/admin/Downloads/code/code_temp/iOS/'
traverse_folder_and_process_cs_files(folder_path)

需要注意的是Windows平台写入utf-8的时候如果没有以下这行代码会自动加上UTF-8 with BOM标记参考UTF-8 with BOM 这行代码也只是替换掉BOM标识解决兼容性或者识别问题

new_content = re.sub(r'\ufeff', '', new_content)

替换前后对比:

!Pasted image 20241112153715.png

!Pasted image 20241112153802.png