问题
阅读一些 C/C++ 项目的代码,发现有些项目是用 GBK 编码,中文注释显示为乱码。看起来很不方便。
做法:
这里把整个项目,都复制一份,转为 UTF-8 编码。
输入: 原始项目的文件夹路径
输出: 转为 UTF-8 编码的项目文件夹路径
另外
我试了 chardet ,但是检测结果很不准确,导致各种报错。所以干脆不用了。 直接默认原始项目都是 gbk 编码的。
而且我只修改 .c, .cpp, .h 这3种文件。其他不变。
import os
import shutil
# import chardet
"""目的:
阅读一些 C/C++ 项目的代码,发现大多数都是用 GBK 编码,中文注释显示为乱码。
看起来很不方便。
这里把整个项目,都复制一份,转为 UTF-8 编码。
用法:
输入: 原始项目的文件夹路径
输出: 转为 UTF-8 编码的项目文件夹路径
"""
def convert_encoding(file_path, target_encoding='utf-8'):
# Read the file with GBK encoding
try:
with open(file_path, 'r', encoding='gbk', errors='ignore') as f:
content = f.read()
except Exception as e:
print(f"Error reading file {file_path} with GBK encoding: {e}")
return
# Write the content with the target encoding
try:
with open(file_path, 'w', encoding=target_encoding, errors='ignore') as f:
f.write(content)
except Exception as e:
print(f"Error writing file {file_path} with encoding {target_encoding}: {e}")
def copy_and_convert_files(src, dst):
if not os.path.exists(dst):
os.makedirs(dst)
for root, dirs, files in os.walk(src):
relative_path = os.path.relpath(root, src)
dest_dir = os.path.join(dst, relative_path)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
for file in files:
src_file_path = os.path.join(root, file)
dest_file_path = os.path.join(dest_dir, file)
if file.endswith(('.c', '.cpp', '.h')):
shutil.copy2(src_file_path, dest_file_path)
convert_encoding(dest_file_path)
else:
shutil.copy2(src_file_path, dest_file_path)
# 示例例子
src = r'C:\Users\Administrator\Videos\NoteGuiApp'
dst = r'C:\Users\Administrator\Videos\NoteGuiApp-new'
copy_and_convert_files(src, dst)