python 转换文件的编码格式

该代码示例展示了如何使用Python的codecs和chardet库来检测并转换非UTF-8编码的文件,主要涉及文件读取、编码检测以及内容重写到新编码的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非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")  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值