2

If I was creating a sparse file from scratch and I wanted to make it the size of n I would use bytestream.seek(n-1) to offset the pointer and then write a single null byte at the end. Much quicker than writing a bytestream of n length!

However, if I've opened said file with open(…,'ab'), seek() is no longer an option, as soon as I call write() the position resets to the end of the file, as stated in the documentation. It seems the only option when using python's ammend is to write each individual null byte.

Is there another way of appending null bytes to a pre-existing file efficiently and quickly?

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
hedgehog90
  • 1,402
  • 19
  • 37
  • Yes, but as stated in the documentation, if you open a file in 'ba' mode (binary+append), seek commands are reverted as soon as you write. Give it a try. – hedgehog90 Jan 10 '19 at 12:51
  • Just found out I can use 'r+b'... I thought in order to append a file I needed the 'a' character. Problem sorted! – hedgehog90 Jan 10 '19 at 13:17

1 Answers1

1

It’s true that append mode defeats seek, but part of the purpose of seek is to be more flexible than append mode. Open in update mode ('r+b') and you can seek to or past the end of the file. (You can seek to but not past the end in text mode.)

Davis Herring
  • 36,443
  • 4
  • 48
  • 76