我正在尝试制作 file2binary
这是我的代码:
with open("myfile.txt","rb") as fp:
print(fp.read())
但它返回这个:
b'helloworld'
这就是我不想要的
不管怎样,有办法以二进制方式打开文件吗?
根据评论,您希望看到每个字节都表示为以 2 为基数的数字。
你可以做这样的事情。主要成分是:
f.read()
返回一个 bytes
对象,该对象表现为可迭代的字节序列(文档)。
使用带有
{ :08b}
格式说明符的 f 字符串是将字节输出为位串的便捷方法。
import os
import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
filename = os.path.join(temp_dir, "hello.bin")
with open(filename, "wb") as f:
f.write("helloworld".encode("utf-8"))
with open(filename, 'rb') as f:
bytes_data = f.read()
for byte in bytes_data:
print(f"{byte:08b}", end=" ")
输出:
01101000 01100101 01101100 01101100 01101111 01110111 01101111 01110010 01101100 01100100