非utf-8文件转换
如果返回数据正常,却无法转换,使用ignore,decode(“utf-8”, “ignore”)
import codecs
import chardet as chardet
def change_encoding(file_path):
# 文件新名称
file = "config.cfg"
with open(file_path, "rb") as f_in:
data = f_in.read()
# code_type 原文件的编码格式提取
code_type = chardet.detect(data)['encoding']
file_convert(file_path, file, code_type, 'UTF-8')
def file_convert(file_path, file, in_code="GBK", out_code="UTF-8"):
"""
该程序用于将目录下的文件从指定格式转换到指定格式,默认的是GBK转到UTF-8
:param file: 文件路径
:param in_code: 输入文件格式
:param out_code: 输出文件格式
:return:
"""
out_path = r"E:\桌面-文件\小工具类"
try:
# ignore 可以忽略不必要的错误导致无法打开
with codecs.open(file_path, 'r', in_code, 'ignore') as f_in:
new_content = f_in.read()
f_out = codecs.open(os.path.join(out_path, file), 'w', out_code)
f_out.write(new_content)
f_out.close()
except IOError as err:
print("I/O error: {0}".format(err))
if __name__ == '__main__':
# 可能是不能直接提取文件内容的文件,需要编码格式转换
change_encoding(r"E:\桌面-文件\小工具类\con.cfg")