Python中,关于读取文件编码解码的问题
2018-11-28 10:46
197 查看
UnicodeDecodeError: 'gbk' codec can't decode byte 0xb1 in position 94: illegal multibyte sequence
有时候用open()方法打开文件读取文件的时候会出现这个问题:‘GBK’编×××无法解码94号位置的字节0xb1:非法多字节序列。错误信息提示了使用“GBK”解码。 1.分析 pycharm自动使用的是‘UTF-8’编码,好像没有什么问题,为什么会出现这个错误呢。结果查了下open()函数的注解,里面又这么一段话: encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. *The default encoding is platform dependent*, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. The default encoding is platform dependent:默认编码方式取决于平台。这也就不奇怪会用‘GBK’编码了,平台不一样,编码方式不一样,所以读取的时候回出现错误。 2.解决方法 # 1.以byte读取,并以‘utf-8’解码 # fp = open(filename, 'rb') # content = fp.read() # self.content = content.decode('utf-8') # fp.close() # 2.在打开文件时指定编码方式 fp = open(filename, encoding='utf-8') content = fp.read() self.content = content fp.close() 如有不同见解,欢迎分享。
相关文章推荐
- 关于Python文档读取UTF-8编码文件问题
- 关于python读取文件编码问题(作弊方法)
- 关于python3.x读取写入文件时编码报错问题
- 关于python编码问题无法读取GBK文件
- [Python爬虫] 中文编码问题:raw_input输入、文件读取、变量比较等str、unicode、utf-8转换问题
- python中写入csv,excel显示、pandas读取csv文件的编码问题
- sublime python3中读取和写入文件时如何解决编码问题
- python2 读取文件TXT编码问题
- Python文件读取编码错误问题解决之(PyCharm开发工具默认设置的坑。。。)
- Python读取UTF-8编码文件并使用命令行执行时输出结果的问题
- python读取文件中的第一行出现编码问题
- rood-Python 3读取.CSV文件遇到的编码问题
- Python 读取文件中unicode编码转成中文显示问题
- 关于Windows系统下,Python读取文件的问题。
- Python读取Excel文件遇到的编码问题(pycharm)
- 关于Python读取文件的路径中斜杠问题
- python 读取excel文件 - 编码是个头疼的问题
- Python_Python2_文件读取时的编码问题
- python中使用文件的读取编码问题和简单正则使用(一)
- python读取文件写入数据库中编码问题