调用tell()
在读取我的 GBK 编码文件时会导致下一次调用 readline()
提出 UnicodeDecodeError
.但是,如果我不调用 tell()
,它不会引发此错误。
C:\tmp>hexdump badtell.txt
000000: 61 20 6B 0D 0A D2 BB B0-E3 a k......
C:\tmp>类型 test.py
with open(r'c:\tmp\badtell.txt', "r", encoding='gbk') as f:
while True:
pos = f.tell()
line = f.readline();
if not line: break
print(line)
C:\tmp>python test.py
a k
Traceback (most recent call last):
File "test.py", line 4, in <module>
line = f.readline();
UnicodeDecodeError: 'gbk' codec can't decode byte 0xd2 in position 0: incomplete multibyte sequence
当我删除
f.tell()
声明,它成功解码。为什么?我在Win7/Win10上试过Python3.4/3.5 x64,都一样。
任何一个,任何想法?我应该报告错误吗?
我有一个大文本文件,我真的很想得到这个大文本的文件位置范围,有解决方法吗?
最佳答案
好的,有一个解决方法,它到目前为止有效:
with open(r'c:\tmp\badtell.txt', "rb") as f:
while True:
pos = f.tell()
line = f.readline();
if not line: break
line = line.decode("gbk").strip('\n')
print(line)
我昨天在这里提交了一个问题:http://bugs.python.org/issue26990
仍然没有回应
关于python-3.x - 为什么 file.tell() 会影响编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37128454/