Python读取Excel文件遇到的编码问题(pycharm)

来源:互联网 发布:高峰于谦 知乎 编辑:程序博客网 时间:2024/05/18 00:25

1.读取中文文件名,出现错误

解决办法:

第一种:把中文换成英文(不要打我),

第二种:

file=u"中国.xls"#这样也可以,前提是这个文件在当前目录下,不然记得写路径data=xlrd.open_workbook(file)
第三种;
file="中国.xls".decode("utf-8")#将中文进行decode解码也就是将utf-8转为unicode
data=xlrd.open_workbook(file)
2.控制台输出中文乱码
解决方法:
print("中国").decode('utf-8').encode('gbk')
#源码是utf-8,控制台是默认gbk输出,
最好自己去更改一下设置就好(在file-settings-fileEncodings-utf-8)两个都选成utf-8,这样就可以直接输出
原因:
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。 
3.decode和encode

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串转换成gb2312编码。

4.UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data错误

为什么有时候必须添加sys.setdefaultencoding('utf-8')

http://blog.csdn.net/crazyhacking/article/details/39375535

不懂,反正加上管用

import sys 
reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,我们需要重新载入 
sys.setdefaultencoding('utf-8') 



原创粉丝点击