我知道如何在 Visual Studio 中更改单个文件的编码,即通过“另存为...”->“使用编码保存”并选择编码。然而,我得到了一个旧的 C++ 代码库,其中包含数百个源文件。有没有办法批量重新编码它们(特别是UTF-8)?我知道
.editorconfig
和类似的编辑器设置,但这些仅影响新创建的文件。
据我所知,Visual Studio、Visual Code、Notepad++等程序不支持此功能。就我而言,我使用了这样的 python 脚本:
import os
import chardet
def convert_to_utf8(folder_path):
extensions = ['.cs', '.js', '.shader', '.compute', '.txt', '.json', '.xml', '.asmdef']
for root, _, files in os.walk(folder_path):
for file in files:
if any(file.endswith(ext) for ext in extensions):
file_path = os.path.join(root, file)
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
encoding = result['encoding']
with open(file_path, 'r', encoding=encoding, errors='ignore') as f:
content = f.read()
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f'Converted: {file_path}')
folder_path = r'C:\UnityProjects\Project\Assets'
convert_to_utf8(folder_path)