由於電腦轉換了編碼為 utf 發現 vs 打開後不少檔案出現轉換提示, 可能是原本開發時直接在 vs 中新增 .cs 文件的緣故, 因為不透過 unity 新增 .cs 文件估計是參考系統編碼, 所以不少文件編碼都是 ascii 格式, 為了解決這個問題弄了個批量轉換工具, 大致如下吧

需要先安裝 chardet 工具

$ pip install chardet 

代碼如下:

import os
import chardet

root_path = r"g:\OlgCase\bbm\source\Unity\Assets\Hotfix"
count = 0
for path, subdirs, files in os.walk(root_path):
for name in files:
    if not name.endswith('cs'):
        continue
    fn = os.path.join(path, name)

    print(fn)
    f = open(fn, mode='rb')
    content = f.read()
    f.close()
    result = chardet.detect(content)

    if result['encoding'] == None:
        print('error')
        continue

    print(result)
    if (result['encoding'] != 'UTF-8-SIG' and
     result['encoding'] != 'UTF-8' and 
     result['encoding'] != 'utf-8'):

        print('process, encoding:' + result['encoding'] + ", fn:" + fn)
        if result["encoding"] == "GB2312":
            result["encoding"] = "GBK"
        with open(fn, "w", encoding="UTF-8-SIG", newline='\n') as file:
            line = str(content, encoding = "GBK")
            print(line)
            file.write(line)
            count +=1
            file.close()

print("轉換檔案數",count)

标签: none

添加新评论