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
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.
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.
"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.
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.
On some systems, 'ab'
forces all writes to happen at the end of the file. You probably want 'r+b'
.
r+b should work as you wish
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With