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.

sifrani
  • 3
  • 3
  • 2
    Does this answer your question? [How to read bits from a file?](https://stackoverflow.com/questions/10689748/how-to-read-bits-from-a-file) – Shay Jan 04 '22 at 08:28

2 Answers2

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='')
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
-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))
shapale
  • 123
  • 2
  • 9
  • 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 – FLAK-ZOSO Jan 04 '22 at 08:47