from chardet import detect as char_detect
def change_encode_type(file_path, des='utf-8'):
# 获取原文本的编码类型
with open(file_path, 'rb') as f:
detect_result = char_detect(f.read(200))
src = detect_result['encoding'].lower()
print('编码检测结果: {},概率: {}'.format(src, detect_result['confidence']))
if src in ['ascii', 'gb2312']:
src = 'gb18030' # win
if src != des:
with open(file_path, 'r', encoding=src) as f:
text = f.read()
with open(file_path, 'w', encoding=des) as f:
f.write(text)
经测试,des为 utf-8可用,其他结果未知