2

I'm trying to figure out how to update the data in a binary file using Python.

I'm already comfortable reading and writing complete files using "array", but I'm having trouble with in place editing.

Here's what I've tried:

my_file.seek(100)

my_array = array.array('B')
my_array.append(0)
my_array.tofile(my_file)

Essentially, I want to change the value of the byte at position 100. The above code does update the value, but then truncates the rest of the file. I want to be able to change the value at position 100, without modifying anything else in the file.

Note that I'm editing multi-gigabyte files, so I don't want to read the entire thing into memory, update memory, and then write back out to disk.

2 Answers 2

5

According to the documentation of open(), you should open the file in 'rb+' mode to avoid the truncating behavior.

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

1 Comment

That was it. Thanks! Since I was opening the file for writing, I had opened it in 'wb+', which made more sense. That's what I get for not reading the docs thoroughly.
1

Are you opening the file in 'r+b' mode?

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.