tags:

views:

97

answers:

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.

+3  A: 

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

Roberto Bonvallet
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.
Eric Reid
+1  A: 

Are you opening in 'r+b' mode?

foosion