python读取txt文件编码格式转换_python 转换文件编码格式成utf8

本文介绍了如何使用Python的chardet库检测文件编码,并通过codecs模块将非UTF-8编码的txt文件转换为UTF-8。通过提供一个脚本,演示了如何遍历指定目录,将特定类型的文件批量转换为UTF-8编码。

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

使用python转换文件编码。写中途遇到问题

不知道文件具体是什么编码

str和unicode没理清,str是字节数组,unicode才是字符串,用type(xx)可获得类型。

搜集的资料

1. 使用chardet检测字符串编码

import chardet

content = open("a.txt","r")# str类型

source_encoding = chardet.detect(content)['encoding']

if source_encoding == None:

print "can not detect"

PS: utf8结果字符串是'utf-8',utf8-bom结果是'UTF-8-SIG'。

2. 使用codecs读写指定格式编码文件

content = codecs.open("a.txt", 'r', "ascii").write(content)

codecs.open("b.txt", 'w', encoding="UTF-8-SIG").write(content)

codecs.open,读取时不指定编码,就和open一样,返回str类型。

3. 综合起来就可以转换了

import chardet

import codecs

def convert_file_to_utf8(filename):

# !!! does not backup the origin file

content = codecs.open(filename, 'r').read()

source_encoding = chardet.detect(content)['encoding']

if source_encoding == None:

print "??",filename

return

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值