INNER CODE UNIT · Python
detect_encoding
KSwordDEV/KSword · KswordHUD/to_u8.py:4
def detect_encoding(file_path):
"""检测文件编码"""
with open(file_path, 'rb') as f:
# 读取前10KB数据用于编码检测,提高准确性
raw_data = f.read(10240)
result = chardet.detect(raw_data)
return result['encoding']
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则跳过