如何使用 python 将文件的位提取为这样的字符串:“
10111010110
”?
我用
open('file','rb').read()
读取字节而不是位。
在 python 10 及更高版本中:
format(int.from_bytes(open('file','rb').read()),'b')
在 python 9 及更低版本中:
format(int.from_bytes(open('file','rb').read(),'big'),'b')
如果 byteorder 为“大”,则最高有效字节位于字节数组的开头。如果 byteorder 为“little”,则最高有效字节位于字节数组的末尾。
如果您以二进制模式打开文件并读取全部内容,您将获得一个字节数组,然后您可以对其进行迭代。然后你可以使用 f-string 来格式化数据。
例如:
with open('foo.bin', 'rb') as data:
for b in data.read():
print(f'{b:08b}')