0

我正在尝试在 Colab 中打开一个使用 gb-2312 编码的文件。这是我在 IDE 中成功运行以读取和解码的代码:

file = open(r'file.txt')
opened = file.read()
decoded = opened.encode('latin1').decode('gb2312')
print(decoded)

当我在 colab 中运行此代码时,我收到以下错误:

'utf-8' codec can't decode byte 0xc6 in position 67: invalid continuation byte

但是如果不先使用 read() 或 list() 就无法解码,否则会出现以下错误:

'_io.TextIOWrapper' object has no attribute 'encode'

这似乎是第 22 条规则。这是 Colab 的一个错误,还是有更好的方法来解决这个问题?

4

1 回答 1

0

打开文件时的默认值为rt(读取,文本模式)并使用由locale.getpreferredencoding(False). 使用encoding参数覆盖默认值(看起来是utf-8):

with open('file.txt', encoding='gb2312') as file:
    data = file.read()
于 2021-02-24T01:26:28.343 回答