4

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?

Petri
  • 4,796
  • 2
  • 22
  • 31

1 Answers1

9

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()
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • Relevant docs are [here](https://docs.python.org/3/library/io.html#io.IOBase.truncate). Note that it reads also "(on most systems, additional bytes are zero-filled)" – Adam Smith Aug 23 '16 at 19:20