Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does truncating a BytesIO mess it up?

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?

like image 968
Petri Avatar asked Oct 20 '25 14:10

Petri


1 Answers

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()
like image 176
Daniel Avatar answered Oct 22 '25 04:10

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!