views:

171

answers:

3

Hi,

I'm trying to read a file byte by byte, but I'm not sure how to do that. I'm trying to do it like that:

file = open(filename, 'rb')
while 1:
   byte = file.read(8)
   # Do something...

So does that make the variable byte to contain 8 next bits at the beginning of every loop? It doesn't matter what those bytes really are. The only thing that matters is that I need to read a file in 8-bit stacks.

EDIT:

Also I collect those bytes in a list and I would like to print them so that they don't print out as ASCII characters, but as raw bytes i.e. when I print that bytelist it gives the result as

['10010101', '00011100', .... ]
+5  A: 

To read one byte:

file.read(1)

8 bits is one byte.

Mark Byers
Thanks. I thought that file.read(1) would read just one bit, but seems it reads one byte.
zaplec
+2  A: 

The code you've shown will read 8 bytes. You could use

with open(filename, 'rb') as f:
   while 1:
      byte_s = f.read(1)
      if not byte_s:
         break
      byte = byte_s[0]
      ...
KennyTM
+2  A: 

To answer the second part of your question, to convert to binary you can use a format string and the ord function:

>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'

Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.

Scott Griffiths