import chardet
import codecs
from django.utils.encoding import smart_text
old = r"C:\Users\administrator\Desktop\qwerty.csv"
def check_file_charset(file):
with open(file, 'rb') as f:
return chardet.detect(f.read())
def Convert_file_character(File_path):
f_type = check_file_charset(File_path)
print (File_path,"字符集为:",f_type['encoding'])
try:
if f_type and 'encoding' in f_type.keys() and f_type['encoding'] != 'utf-8':
with codecs.open(File_path, 'rb', f_type['encoding'],errors='ignore') as f:
content = smart_text(f.read())
with codecs.open(File_path, 'wb', 'utf-8') as f:
f.write(content)
print ("字符集转换成功")
else:
print("字符集为 utf-8,不需要进行转换")
except Exception as ERR:
print("字符集转换失败")
print (ERR)
Convert_file_character(old)