How to seek and append to a binary file in python?

Kennedy picture Kennedy · Dec 8, 2010 · Viewed 42.5k times · Source

I am having problems appending data to a binary file. When i seek() to a location, then write() at that location and then read the whole file, i find that the data was not written at the location that i wanted. Instead, i find it right after every other data/text.

My code

file = open('myfile.dat', 'wb')
file.write('This is a sample')
file.close()

file = open('myfile.dat', 'ab')
file.seek(5)
file.write(' text')
file.close()

file = open('myfile.dat', 'rb')
print file.read()  # -> This is a sample text

You can see that the seek does not work. How do i resolve this? are there other ways of achieving this?

Thanks

Answer

Marcelo Cantos picture Marcelo Cantos · Dec 8, 2010

On some systems, 'ab' forces all writes to happen at the end of the file. You probably want 'r+b'.