python 将任意字符集文件转换为 utf8 字符集文件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值