Why does truncating a BytesIO mess it up?

血红的双手。 提交于 2019-12-24 07:45:01

问题


Running this on Python 3.5.1 on OSX:

import io

b = io.BytesIO()

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

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

Produces:

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

So truncating the BytesIO somehow causes it to start inserting extra zero bytes in the beginning? Why?


回答1:


truncate does not move the file pointer. So the next byte is written to the next position. You have also to seek to the beginning:

b.seek(0)
b.truncate()


来源:https://stackoverflow.com/questions/39109068/why-does-truncating-a-bytesio-mess-it-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!