3

在 OSX 上的 Python 3.5.1 上运行它:

import io

b = io.BytesIO()

b.write(b'222')
print(b.getvalue())

b.truncate(0)
b.write(b'222')
print(b.getvalue())

产生:

b'222'
b'\x00\x00\x00222'

那么以BytesIO某种方式截断会导致它开始在开头插入额外的零字节?为什么?

4

1 回答 1

7

truncate不移动文件指针。所以下一个字节被写入下一个位置。你还必须从头开始:

b.seek(0)
b.truncate()
于 2016-08-23T19:19:47.127 回答