Reputation: 457
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.
Upvotes: 2
Views: 1645
Reputation: 33319
According to the documentation of open()
, you should open the file in 'rb+'
mode to avoid the truncating behavior.
Upvotes: 5