为什么截断 BytesIO 会把它搞砸?

Why does truncating a BytesIO mess it up?

运行 Python 3.5.1 OSX:

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 会导致它开始在开头插入额外的零字节?为什么?

truncate 不移动文件指针。所以下一个字节被写入下一个位置。你也得找开头:

b.seek(0)
b.truncate()