Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python read binary from specific position

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,

like image 902
Matej Avatar asked Oct 10 '11 13:10

Matej


People also ask

How do I read a binary file in Python?

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() ...

How do I read a binary image in Python?

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.

How do I read an offset file in Python?

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.


1 Answers

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

like image 120
Grim Avatar answered Oct 20 '22 01:10

Grim