如何在python中将整数列表写入二进制文件 [英] How to write a list of integers to a binary file in python

查看:866
本文介绍了如何在python中将整数列表写入二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代表代码字节的整数列表.如何快速,高效地将它们写入二进制文件.

I have a list of integers which represent bytes of code. How can I write them to a binary file fast and more efficiently.

我尝试过:

with open (output1, "wb") as compdata:
    for row in range(height):
        for data in cobs(delta_rows[row].getByte_List()):
            output_stream.append(Bits(uint=data, length=8))
    compdata.write(output_stream.tobytes())

with open (output1, "wb") as compdata:
    for row in range(height):
        bytelist = cobs(delta_rows[row].getByte_List())
        for byte in bytelist:
            compdata.write(chr(byte))

两者都能给我带来我认为是正确的结果(我尚未扭转这一过程),但都需要花费很长时间(分别为6分钟和4分钟).

both get me a result which I think is correct (I have yet to reverse the process) but both take a long time (6min and 4min respectfully).

推荐答案

使用 bytearray()对象,直接将其写入输出文件:

Use a bytearray() object, write that straight to the output file:

with open (output1, "wb") as compdata:
    for row in range(height):
        bytes = bytearray(cobs(delta_rows[row].getByte_List()))
        compdata.write(bytes)

bytearray()将整数序列解释为字节值序列.

A sequence of integers is interpreted by a bytearray() as a sequence of byte values.

在Python 3中,您可以使用 bytes()类型同样,具有相同的输入;毕竟,您在创建后不会改变这些值.

In Python 3, you can use a bytes() type as well, with the same input; you are not mutating the values after creation, after all.

这篇关于如何在python中将整数列表写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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