Eric Reid
Eric Reid

Reputation: 457

Updating value in binary file with Python

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

Answers (2)

foosion
foosion

Reputation: 7898

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

Upvotes: 1

Roberto Bonvallet
Roberto Bonvallet

Reputation: 33319

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

Upvotes: 5

Related Questions