Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get file data as binary in Python?

I am trying to make file2binary
Here’s my code:

with open("myfile.txt","rb") as fp:
    print(fp.read())

But it returns this:

b'helloworld'

And thats what i dont want
Anyways theres way to open file as binary?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Based on the comments, you want to see each byte represented as base-2 digits.

You can do something like this. The key ingredients are:

  1. f.read() on a file opened in binary mode returns a bytes object, which behaves as an iterable sequence of bytes (documentation).

  2. Using an f-string with the { :08b} format specifier is a convenient way to output a byte as a string of bits.

import os
import tempfile

with tempfile.TemporaryDirectory() as temp_dir:
    filename = os.path.join(temp_dir, "hello.bin")
    with open(filename, "wb") as f:
        f.write("helloworld".encode("utf-8"))

    with open(filename, 'rb') as f:
        bytes_data = f.read()

for byte in bytes_data:
    print(f"{byte:08b}", end=" ")

Output:

01101000 01100101 01101100 01101100 01101111 01110111 01101111 01110010 01101100 01100100 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading