Credit: Luther Blissett
You want to read a binary record from somewhere inside a large file of fixed-length records, without reading a record at a time to get there.
The byte offset of the start of a record in the file is the record size multiplied by the record number (counting from 0). So just seek, then read:
thefile = open('somebinfile', 'rb') thefile.seek(record_size * record_number) buffer = thefile.read(record_size)
This approach works only on files (generally binary ones) defined in
terms of records that are all the same, fixed size; it
doesn’t on normal text files. For clarity, the
recipe shows the file being opened for reading as a binary file, by
passing 'rb'
as the second argument to
open
. Of course, you don’t need
to open the file just before performing the first
seek
on it. As long as the file object is open for
reading as a binary file, you can perform as many
seek
and read
operations as you
want before eventually closing the file again.
Get Python Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.