Python编写二进制

2022-01-09 00:00:00 python python-3.x file binary

问题描述

我使用 python 3我尝试将二进制文件写入我使用 r+b 的文件.

I use python 3 I tried to write binary to file I use r+b.

for bit in binary:
    fileout.write(bit)

其中 binary 是一个包含数字的列表.如何将其写入二进制文件?

where binary is a list that contain numbers. How do I write this to file in binary?

最终文件必须看起来像b' x07x08x07

The end file have to look like b' x07x08x07

谢谢


解决方案

当您以二进制模式打开文件时,您实际上是在使用 bytes 类型.因此,当您写入文件时,您需要传递一个 bytes 对象,而当您从中读取时,您会得到一个 bytes 对象.相反,当以文本模式打开文件时,您正在使用 str 对象.

When you open a file in binary mode, then you are essentially working with the bytes type. So when you write to the file, you need to pass a bytes object, and when you read from it, you get a bytes object. In contrast, when opening the file in text mode, you are working with str objects.

所以,写二进制"其实就是写字节串:

So, writing "binary" is really writing a bytes string:

with open(fileName, 'br+') as f:
    f.write(b'x07x08x07')

如果你有实际的整数想要写成二进制,你可以使用 bytes 函数将整数序列转换为字节对象:

If you have actual integers you want to write as binary, you can use the bytes function to convert a sequence of integers into a bytes object:

>>> lst = [7, 8, 7]
>>> bytes(lst)
b'x07x08x07'

结合这一点,您可以将整数序列作为字节对象写入以二进制模式打开的文件中.

Combining this, you can write a sequence of integers as a bytes object into a file opened in binary mode.

正如 Hyperboreus 在评论中指出的那样,bytes 只会接受实际上适合一个字节的数字序列,即 0 到 255 之间的数字.如果你想存储任意(正)整数以它们的方式,不必费心知道它们的确切大小(这是结构所必需的),然后您可以轻松编写一个辅助函数,将这些数字分成单独的字节:

As Hyperboreus pointed out in the comments, bytes will only accept a sequence of numbers that actually fit in a byte, i.e. numbers between 0 and 255. If you want to store arbitrary (positive) integers in the way they are, without having to bother about knowing their exact size (which is required for struct), then you can easily write a helper function which splits those numbers up into separate bytes:

def splitNumber (num):
    lst = []
    while num > 0:
        lst.append(num & 0xFF)
        num >>= 8
    return lst[::-1]

bytes(splitNumber(12345678901234567890))
# b'xabTxa9x8cxebx1f
xd2'

因此,如果您有一个数字列表,则可以轻松地遍历它们并将每个数字写入文件;如果您想稍后单独提取数字,您可能需要添加一些东西来跟踪哪些单个字节属于哪些数字.

So if you have a list of numbers, you can easily iterate over them and write each into the file; if you want to extract the numbers individually later you probably want to add something that keeps track of which individual bytes belong to which numbers.

with open(fileName, 'br+') as f:
    for number in numbers:
        f.write(bytes(splitNumber(number)))

相关文章