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.
-
2Does this answer your question? How to read bits from a file?Shay– Shay2022-01-04 08:28:40 +00:00Commented Jan 4, 2022 at 8:28
Add a comment
|
2 Answers
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='')
Comments
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
FLAK-ZOSO
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