python批量添加宏.md 1.4 KB

#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]]