How to Read Bytes from a file

Jussi Salmela tiedon_jano at hotmail.com
Thu Mar 1 16:29:15 CET 2007


Bart Ogryczak kirjoitti:
> On Mar 1, 7:52 am, "gregpin... at gmail.com" <gregpin... at gmail.com>
> wrote:
>> It seems like this would be easy but I'm drawing a blank.
>>
>> What I want to do is be able to open any file in binary mode, and read
>> in one byte (8 bits) at a time and then count the number of 1 bits in
>> that byte.
>>
>> I got as far as this but it is giving me strings and I'm not sure how
>> to accurately get to the byte/bit level.
>>
>> f1=file('somefile','rb')
>> while 1:
>>     abyte=f1.read(1)
> 
> import struct
> buf = open('somefile','rb').read()
> count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+
> (x&64>0)+(x&128>0)
> byteOnes = map(count1,struct.unpack('B'*len(buf),buf))
> 
> byteOnes[n] is number is number of ones in byte n.
> 
> 
> 

I guess struct.unpack is not necessary, because:

	byteOnes2 = map(count1, (ord(ch) for ch in buf))

seems to do the trick also.

Cheers,
Jussi



More information about the Python-list mailing list