4.14 Using Random-Access Input/Output
Credit: Luther Blissett
4.14.1 Problem
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.
4.14.2 Solution
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)
4.14.3 Discussion
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.
4.14.4 See Also
The section of the Library Reference on file
objects; Perl Cookbook Recipe 8.12.
|