Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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', .... ] 
like image 662
zaplec Avatar asked May 20 '10 09:05

zaplec


People also ask

How do you read and print binary files in Python?

Python read binary file into numpy array First, import numpy as np to import the numpy library. Next, open the binary file in reading mode. Now, create the NumPy array using the fromfile() method using the np object. Parameters are the file object and the datatype initialized as bytes.

How do you read a single byte of data in Python?

you can use bin(ord('b')). replace('b', '') bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.

How do you convert bytes to binary in Python?

Let us see how to write bytes to a file in Python. First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.


2 Answers

To read one byte:

file.read(1) 

8 bits is one byte.

like image 99
Mark Byers Avatar answered Oct 04 '22 14:10

Mark Byers


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.

like image 38
Scott Griffiths Avatar answered Oct 04 '22 15:10

Scott Griffiths