0

I would like an output like 01100011010... or [False,False,True,True,False,...] from a file to then create an encrypted file. I've already tried byte = file.read(1) but i don't know how to then convert it to bits.

1

2 Answers 2

0

You can read a file in binary mode this way:

with open(r'path\to\file.ext', 'rb') as binary_file:
    bits = binary_file.read()

The 'rb' option stands for Read Binary.


For the output you asked for you can do something like this:

[print(bit, end='') for bit in bits]

that is the list comprehension equivalent to:

for bit in bits:
    print(bit, end='')

Since 'rb' gives you hex numbers instead of bin, you can use the built-in function bin to solve the problem:

with open(r'D:\\help\help.txt', 'rb') as file:
    for char in file.read():
        print(bin(char), end='')
Sign up to request clarification or add additional context in comments.

Comments

-1

Suppose we have text file text.txt

# Read the content:
with open("text.txt") as file:
  content=file.read()
# using join() + bytearray() + format()
# Converting String to binary
res = ''.join(format(i, '08b') for i in bytearray(content, encoding ='utf-8'))
  
# printing result 
print("The string after binary conversion : " + str(res))

1 Comment

It's unefficient reading the file, converting it to a string (yes, it's what file.read() does), and then converting it to binary. Why ,you don't simply open the file as binary? Anyways I've much apreciated the inline assigation to res, it's really pythonic

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.