I have a huge binary file from which I want to read some bytes from exact positions in the file. How can I access specific bytes from binary file not having to loop through all bytes from the beginning of the file? Thanx,
To read from a binary file, we need to open it with the mode rb instead of the default mode of rt : >>> with open("exercises. zip", mode="rb") as zip_file: ... contents = zip_file. read() ...
The open() function opens a file in text format by default. To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing.
Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer within the file.
Make sure you open the file with the "b" attribute (for example: file("myfile.bin", "rb")
). Then use the seek()
method of the file object.
Look here: http://docs.python.org/release/2.4.4/lib/bltin-file-objects.html
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