Question about binary file reading

Tino Wildenhain tino at wildenhain.de
Wed Mar 4 18:28:32 EST 2009


Rhodri James wrote:
> On Wed, 04 Mar 2009 22:58:38 -0000, vibgyorbits <bkajey at gmail.com> wrote:
> 
>> I'm writing a tool to do some binary file comparisons.
>> I'm opening the file using
>>
>> fd=open(filename,'rb')
>>
>> # Need to seek to 0x80 (hex 80th) location
>>
>> fd.seek(0x80)
>>
>> # Need to read just 8 bytes and get the result back in hex format.
>> x=fd.read(8)
>> print x
>>
>> This prints out garbage. I would like to know what am i missing here.
> 
> Your bytes are being interpreted as characters when you print the 
> buffer, and the chance of them being meaningful text is probably small.  
> Try the following:
> 
> for b in x:
>     print hex(ord(b))
> 

better:

print x.encode("hex")

Cheers
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20090305/0834655a/attachment-0001.bin>


More information about the Python-list mailing list