Python的写作二进制 [英] Python writing binary

查看:137
本文介绍了Python的写作二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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)

其中二进制是包含数字的列表。
我怎样写这在二进制文件?

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

文件的末尾有看起来像
B'X07 \\ X08 \\ X07 \\

The end file have to look like b' x07\x08\x07\

感谢

推荐答案

当你以二进制模式打开一个文件,那么你基本上是用的 字节 类型。所以,当你写文件,你需要通过字节对象,当你从它读,你会得到一个字节对象。相反,在文本模式下打开文件时,您使用 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'\x07\x08\x07')

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

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'\x07\x08\x07'

复合使用,你可以写整数作为一个字节对象的序列成二进制模式打开的文件。

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

由于Hyperboreus在评论中指出,字节将只接受真正适合一个字节,即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'\xabT\xa9\x8c\xeb\x1f\n\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)))

这篇关于Python的写作二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆