Reading file bit by bit

Peter Otten __peter__ at web.de
Mon Jun 7 05:17:27 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.
> 
> Any help on doing the actual file reading is appreciated.

The logical unit in which files are written is the byte. You can split the 
bytes into 8 bits...

>>> def bits(f):
...     while True:
...             b = f.read(1)
...             if not b: break
...             b = ord(b)
...             for i in range(8):
...                     yield b & 1
...                     b >>= 1
...
>>> with open("tmp.dat", "wb") as f: # create a file with some example data
...     f.write(chr(0b11001010)+chr(0b10101111))
>>> with open("tmp.dat", "rb") as f:
...     for bit in bits(f):
...             print bit
...
0
1
0
1
0
0
1
1
1
1
1
1
0
1
0
1

but that's a very inefficient approach. If you explain what you are planning 
to do we can most certainly come up with a better alternative.

Peter



More information about the Python-list mailing list