Files
FileCodeBox/encoding_convert.py
T

22 lines
579 B
Python
Raw Normal View History

2023-01-07 12:09:25 +08:00
# 获取文件编码
2023-01-03 21:10:38 +08:00
import chardet
def get_encoding(file):
with open(file, 'rb') as f:
return chardet.detect(f.read())['encoding']
2023-01-07 12:09:25 +08:00
# 将其他编码的文件转换为UTF-8编码
def other2utf8(file, encoding):
with open(file, 'r', encoding=encoding) as f:
lines = f.readlines()
with open(file, 'w', encoding='utf-8') as f:
f.writelines(lines)
2023-01-03 21:10:38 +08:00
# 获取文件编码,如果为utf-8编码,就转换为gbk编码
def convert_encoding(file):
2023-01-07 12:09:25 +08:00
encoding = get_encoding(file)
if encoding != 'utf-8':
other2utf8(file, encoding)