Reading file bit by bit

Ulrich Eckhardt eckhardt at satorlaser.com
Mon Jun 7 05:12:05 EDT 2010


Alfred Bovin wrote:
> I'm working on something where I need to read a (binary) file bit by bit
> and do something depending on whether the bit is 0 or 1.

Well, smallest unit you can read is an octet/byte. You then check the
individual digits of the byte using binary masks.


   f = open(...)
   data = f.read()
   for byte in data:
       for i in range(8):
           bit = 2**i & byte
           ...

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list