Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

seek

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

like image 988
Kennedy Avatar asked Dec 08 '10 13:12

Kennedy


People also ask

How do you update a binary file in Python?

Give value of roll number from user using input() function and store it in variable say roll. Open binary file say 'student. dat' in rb+( read and binary mode) and store it in file object say 'file' Use load method to read binary file data and pass file object say 'file' as an argument to load method of pickle module.

How do I search a binary file?

Enter "bin" without quotes into the search bar to locate all straight Binary files on your computer. This locates all files with the ". bin" extension. Enter "exe" into the search bar instead to locate all executable binary files.

What is binary file mode for append?

"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like GIFs, audio files like MP3s or binary document formats like Word or PDF. To open files in binary append mode, when specifying a mode, add 'ab' to it.

Does SEEK () work for binary files?

Example 2: Seek() function with negative offset only works when file is opened in binary mode. Let's suppose the binary file contains the following text. b'Code is like humor.


2 Answers

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

like image 164
Marcelo Cantos Avatar answered Oct 13 '22 19:10

Marcelo Cantos


r+b should work as you wish

like image 5
rob Avatar answered Oct 13 '22 17:10

rob