如何在Python中获取二进制文件数据?

问题描述 投票:0回答:1

我正在尝试制作 file2binary
这是我的代码:

with open("myfile.txt","rb") as fp:
    print(fp.read())

但它返回这个:

b'helloworld'

这就是我不想要的
不管怎样,有办法以二进制方式打开文件吗?

python file binary
1个回答
1
投票

根据评论,您希望看到每个字节都表示为以 2 为基数的数字。

你可以做这样的事情。主要成分是:

    以二进制模式打开的文件上的
  1. f.read()
    返回一个
    bytes
    对象,该对象表现为可迭代的字节序列(文档)。

  2. 使用带有

    {  :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 
© www.soinside.com 2019 - 2024. All rights reserved.