gpt4 book ai didi

python - 在python中读取dat文件显示UnicodeDecodeError(文件)

转载 作者:行者123 更新时间:2023-12-03 08:42:12 24 4
gpt4 key购买 nike

我尝试打开一个dat文件,但遇到UnicodeDecode错误。

请参阅以下我尝试过的代码。

with open(dat_file, 'r') as f:  (or)  with open(dat_file, 'r', errors = 'ignore') as f
print('type of f :', type(f)) # for ref
print('f : ', f) # for ref

data = f.read()
print(data)

for lines in data:
print(lines)

Error

type of f : <class '_io.TextIOWrapper'>
f : <_io.TextIOWrapper name='...\\dat_file\\test.dat' mode='r' encoding='cp1252'>

Traceback (most recent call last):

File "<ipython-input-30-64afc3b0473f>", line 5, in <module>
data = f.read()

File "...anaconda3\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 22332: character maps to <undefined>


当我打开 data in Variable explorer时,它看起来像..

enter image description here

需求

替代溶液:

如果我尝试转换 the dat file to .mat文件 using matlab.
如果我使用 scipy.io作为 f = sio.loadmat(file.mat).打开mat文件

如果我打开变量浏览器,它将作为字典打开,并且我可以继续通过该词典进行工作。 f = enter image description here

要求:

但是我想直接在python中打开dat文件,在python中读取时遇到错误。

任何线索都将非常有帮助。

最佳答案

尝试将模式更改为“rb”,b表示python将逐字节读取对象,而不是逐字符读取。
由于(unicode-)字符可以由多个字节组成,因此可能会发生读取与Unicode字符不对应的某些字节组合的情况,从而导致错误。

有关更多信息,请在交互式python控制台中键入help(open)。
help()通常是一个很好的资源:)

关于python - 在python中读取dat文件显示UnicodeDecodeError(文件<class '_io.TextIOWrapper'>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60848668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com