Read binary file and dump data in

Chris Rebert clp2 at rebertia.com
Tue Jan 13 15:50:10 EST 2009


On Tue, Jan 13, 2009 at 12:02 PM, Santiago Romero <sromero at gmail.com> wrote:
>
>  Hi.
>
>  Until now, all my python programs worked with text files. But now I'm
> porting an small old C program I wrote lot of years ago to python and
> I'm having problems with datatypes (I think).
>
>  some C code:
>
>  fp = fopen( file, "rb");
>  while !feof(fp)
>  {
>    value = fgetc(fp);
>    printf("%d", value );
>  }
>
>  I started writing:
>
>  fp = open(file, "rb")
>  data = fp.read()
>  for i in data:
>   print "%d, " % (int(i))
>
>  But it complains about i not being an integer... . len(data) shows
> exactly the file size, so maybe is a "type cast" problem... :-?
>
>  What's the right way to work with the binary data (read 1 byte values
> and work with them, dumping them as an integer in this case)?

Albert already pointed out the problem with using int(), so I'll just
say that you might be interested in the `struct` module:
http://docs.python.org/library/struct.html

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list