使用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
conten