sehrrehs 发表于 2020-4-2 05:22:17

第28课 txt文件不能readline

当我试图用 f=open() 打开一个txt文件并且 readline() 的时候,会报 UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 44: character maps to <undefined> 错误,这个怎么解决呢,求助!

l=open('C:\\Users\\Zhang\\Desktop\\xiaohua.txt','r')
l.readline()

报错的具体内容:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
    l.readline()
File "D:\python\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 44: character maps to <undefined>

倒戈卸甲 发表于 2020-4-2 07:24:55

错误提示是解码异常,出现了无法解码的字符。这说明相对于你当前(也即是默认的字符集)字符集太小了,应该换成编码更广的字符集

heidern0612 发表于 2020-4-2 07:45:43

l=open('C:\\Users\\Zhang\\Desktop\\xiaohua.txt','r',encoding='UTF-8')
l.readline()
试试

Twilight6 发表于 2020-4-2 08:46:33

应该是编码的问题 在 open()里面多加一项encoding = 'utf-8'   把编码转成utf-8就能解决问题了

zltzlt 发表于 2020-4-2 13:02:22

你的文件内容是什么?

可以试试这样:

l=open('C:\\Users\\Zhang\\Desktop\\xiaohua.txt','r', encodin="utf-8")
l.readline()

lixiangyv 发表于 2020-4-3 10:16:37

报得错误类型是 UnicodeDecodeError ,也就是 编码出现错误,

将 encoding 的编码设置成 'utf-8'

代码:l=open('C:\\Users\\Zhang\\Desktop\\xiaohua.txt','r', encoding="utf-8")
l.readline()
页: [1]
查看完整版本: 第28课 txt文件不能readline