小编mfm*_*ain的帖子

为什么 file.tell() 会影响编码?

调用tell()在阅读我的GBK编码的文件会导致下一次调用readline()来养UnicodeDecodeError。但是,如果我不调用tell(),则不会引发此错误。

C:\tmp>hexdump badtell.txt

000000: 61 20 6B 0D 0A D2 BB B0-E3                       a k......
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

当我删除该f.tell()语句时,它成功解码。为什么?我在Win7/Win10上试过Python3.4/3.5 x64,都是一样的。

任何人,任何想法?我应该报告错误吗? …

file-io character-encoding python-3.x gbk

5
推荐指数
1
解决办法
106
查看次数

标签 统计

character-encoding ×1

file-io ×1

gbk ×1

python-3.x ×1