python判断文件使用什么编码方式编码的。

# 说明:UTF兼容ISO8859-1和ASCII,GB18030兼容GBK,GBK兼容GB2312,GB2312兼容ASCII
CODES = ['UTF-8', 'UTF-16', 'GB18030', 'BIG5']
# UTF-8 BOM前缀字节
UTF_8_BOM = b'\xef\xbb\xbf'




# 获取文件编码类型
def file_encoding(file_path):
    """
    获取文件编码类型\n
    :param file_path: 文件路径\n
    :return: \n
    """
    with open(file_path, 'rb') as f:
        return string_encoding(f.read())




# 获取字符编码类型
def string_encoding(b: bytes):
    """
    获取字符编码类型\n
    :param b: 字节数据\n
    :return: \n
    """
    # 遍历编码类型
    for code in CODES:
        try:
            b.decode(encoding=code)
            if 'UTF-8' == code and b.startswith(UTF_8_BOM):
                return 'UTF-8-SIG'
            return code
        except Exception:
            continue
    return '未知的字符编码类型'
if __name__ == '__main__':
    encoding = file_encoding('2.txt')
    print(encoding)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值