INNER CODE UNIT · Python
convert_to_utf8
KSwordDEV/KSword · KswordHUD/to_u8.py:12
def convert_to_utf8(file_path):
"""将文件转换为UTF-8编码"""
try:
# 检测当前编码
encoding = detect_encoding(file_path)
if not encoding:
print(f"⚠️ 无法检测 {file_path} 的编码,跳过处理")
return False
# 如果已经是UTF-8则跳过
if encoding.lower() in ['utf-8', 'utf-8-sig']:
print(f"ℹ️ {file_path} 已是UTF-8编码,无需转换")
return True
# 读取文件内容
with open(file_path, 'r', encoding=encoding, errors='replace') as f:
content = f.read()