
开篇寄语
最近伯衡君在学习python的过程中,读取txt文本时,在pycharm这个编辑器中出现了下面这段话:"UnicodeDecodeError:'gbk' codec can't decode byte 0x80 in position 0 illegal multibyte sequence",伯衡君一看就知道,肯定是无法读取中文字符才出现这个问题的,那么该如何解决呢?请看这篇。
内容详情
先来说一下,在python中阅读txt文件,有三种主要方法,分别是这个样子:
- read():显示txt文件全文
f = open("demofile.txt", "r") print(f.read())
- readline():显示txt文件,每次打印显示一行
f = open("demofile.txt", "r") print(f.readline())
- readlines():显示txt文件所有行,放在1个列表内
f = open("demofile.txt", "r") print(f.readlines())
不过,这三种方式都无法显示中文,都会显示"UnicodeDecodeError:'gbk' codec can't decode byte 0x80 in position 0 illegal multibyte sequence"。
解决办法其实非常简单,只需要打开支持"UTF-8"这种编码就行了,可以这样书写代码阅读txt文件:
with open("a.txt", "r", encoding='UTF-8') as f: print(f.read()) f.close()
加一个encoding即可,很简单吧。
- 我的微信
- 微信扫一扫加好友
-
- 我的微信公众号
- 扫描关注公众号
-