How to read a file byte by byte in Python and how to print a bytelist as a binary?

Posted by zaplec on Stack Overflow See other posts from Stack Overflow or by zaplec
Published on 2010-05-20T09:14:57Z Indexed on 2010/05/20 14:40 UTC
Read the original article Hit count: 287

Filed under:
|
|

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', .... ]

© Stack Overflow or respective owner

Related posts about python

Related posts about fileopen