【发布时间】:2022-01-04 08:26:24
【问题描述】:
我想从文件中输出类似 01100011010... 或 [False,False,True,True,False,...] 的输出,然后创建加密文件。
我已经尝试过 byte = file.read(1),但我不知道如何将其转换为位。
【问题讨论】:
-
这能回答你的问题吗? How to read bits from a file?
我想从文件中输出类似 01100011010... 或 [False,False,True,True,False,...] 的输出,然后创建加密文件。
我已经尝试过 byte = file.read(1),但我不知道如何将其转换为位。
【问题讨论】:
您可以通过这种方式以二进制模式读取文件:
with open(r'path\to\file.ext', 'rb') as binary_file:
bits = binary_file.read()
'rb' 选项代表Read Binary。
对于您要求的输出,您可以执行以下操作:
[print(bit, end='') for bit in bits]
这就是列表推导等价于:
for bit in bits:
print(bit, end='')
由于'rb'给你的是hex数字而不是bin,你可以使用内置函数bin来解决这个问题:
with open(r'D:\\help\help.txt', 'rb') as file:
for char in file.read():
print(bin(char), end='')
【讨论】:
假设我们有文本文件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))
【讨论】: