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?

2
  • 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. Commented Jan 10, 2019 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! Commented Jan 10, 2019 at 13:17

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.