-3

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?

Kirill
  • 55
  • 1
  • 4

1 Answers1

1

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 
slothrop
  • 3,218
  • 1
  • 18
  • 11