parse binary file in python?
Michael Hudson
mwh at python.net
Mon Jan 19 06:23:10 EST 2004
Andreas Røsdal <andrearo at stud.ntnu.no> writes:
> On Sun, 18 Jan 2004, "Martin v. Löwis" wrote:
> > Andreas Røsdal wrote:
> > > I want to parse a binary file in python. Does
> > > python have some built in methods for doing this easily?
> > > Any links to example code would be nice..
> >
> > Depends on the kind of parsing you want to do. Python
> > can naturally represent binary files in string objects,
> > e.g.
> >
> > f = open("binaryfile.bin", "rb") # notice the b for binary mode
> > data = f.read()
> > f.close()
> >
> > You can then look at the individual bytes by index.
>
> Thanks. Just wanting to know if I understood your answer correctly;
> will the data variable above be an array of binary data,
> eg. data[220] == 0, and data[221] == 1 etc?
No, it's a string, but you can get what you want by using the `ord'
builtin function or the array module or the struct module (or probably
various other ways).
Cheers,
mwh
--
To summarise the summary of the summary:- people are a problem.
-- The Hitch-Hikers Guide to the Galaxy, Episode 12
More information about the Python-list
mailing list