Reading a binary file in as hex
Alex Martelli
aleaxit at yahoo.com
Tue Oct 17 18:12:59 EDT 2000
"Grant Edwards" <grante at visi.com> wrote in message
news:1h3H5.1688$FU3.403358 at ptah.visi.com...
[snip]
> If you want to read the bytes in a file and convert each to a
> hex string, you can do something like this:
>
> import string
> d = open("file.data","rb").read()
> l = map(lambda x: '%02x' % ord(x), d)
> s = string.join(l)
> print s
>
> Or mashed into a one-liner:
>
> string.join(map(lambda x: '%02x' % ord(x), open("file.data","rb").read()))
>
> If you've got Python 2.0 you can use a list comprehension
> rather than the Schemesque map/lambda
In other words...:
s = ''.join(['%02x'%c for c in open('file.data','rb').read()])
(and if map/lambda is Schemesque, surely list comprehensions
are Hasquellish...?-).
Alex
More information about the Python-list
mailing list