Reading from a binary file in a portable way
John Purser
NO_SPAM_jmpurser2 at attbi.com
Thu Apr 18 12:03:31 EDT 2002
"Steve Holden" <sholden at holdenweb.com> wrote in message
news:p9yv8.11123$eS3.9630 at atlpnn01.usenetserver.com...
> "jb" <egrossde at yahoo.de> wrote ...
> >
> > I should like to read a (binary) file x.y in a buffer and then do things
> > like getting the 16 bit integer that is at the offset n, n+1 in the file
> > (maybe lowbyte, then higyhbyte.
> >
> > Previously I did it only under MS-Windows where for example I could open
> the
> > file with the flag O_BINARY but this is no longer possible under Linux.
> >
> > What would a solution that works under both Unix and MS-Windows look
like?
> >
> Such a solution would probably use the mmap module. Although there are
minor
> differences on the two platforms it should be possible to write something
> that works well on both.
>
> regards
> Steve
I just did this. An outline of my code would look like:
import struct
fInput = file('im1.d', 'r+b')
fInput.seek(512)
record = fInput.read(180)
item_number = struct.unpack('> i', record[1:5])
print item_number
fInput.close()
It worked nicely on Windows 2000 (Python 2.2) and Debian Linux (Python 2.1).
I was reading and writing to the input file and needed data from the whole
record so there's some extra lines. I'd suggest writing a fuction that
positioned the file pointer in the correct position based on record number,
record length, data slice, header, etc.
Good Luck,
John Purser
More information about the Python-list
mailing list