今天真的被编码问题一直困扰着,午休都没进行。也真的见识到了各种编码。例如:gbk,unicode、utf-8、ansi、gb2312等。
如果脚本程序中编码与文件编码不一致,就会报出UnicodedecodeError的错误。
1.情景一
- 读文件时常需要将内容转为utf8,文字可正常显示,但是如果原文件内容编码格式不是utf8就会报错UnicodedecodeError。如下:
- 问题:
try:
fileObj = open(os.path.join(path,filename),'r')
textLines = fileObj.readlines()
fileObj.close()
except IOError as err:
print('打开文件%s失败:%s'%(filename,err))
try:
fileObj = open(os.path.join(path,filename),'r',encoding='utf-8')
textLines = fileObj.readlines()
fileObj.close()
except IOError