【问题标题】:How to write a list of integers to a binary file in python如何在python中将整数列表写入二进制文件
【发布时间】:2013-10-09 03:58:32
【问题描述】:

我有一个表示代码字节的整数列表。我怎样才能更快更高效地将它们写入二进制文件。

我试过了:

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 分钟)。

【问题讨论】:

  • 这是 Python 2 还是 3?
  • 对不起 Python 2(特别是 2.7.5)
  • 你看过 struct.Pack 吗?这允许您将二进制数据写入字符串(和文件)。 docs.python.org/2/library/struct.html
  • 首先 - 每 {row, n rows, something} 只写入一次以获得更好的性能。但是 stream.to_bytes() 调用是否也会清除它?否则,您将处于指数级领域……例如。你添加[1,2,3]。您将 [1] 添加到 output_stream,然后将其写入。然后你追加 2,output_stream 现在是 [1,2],然后你写它。然后你追加 3,output_stream 现在是 [1,2,3],然后你写出来。
  • @CorleyBrigman 是的,当我在 SE 上写下来时,我缩进错了。两段代码输出完全相同的数据。

标签: python performance file list


【解决方案1】:

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

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

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

在 Python 3 中,您也可以使用 bytes() type,输入相同;毕竟,您不会在创建后改变值。

【讨论】:

  • 我已经尝试在我的代码中实现这个解决方案,它也有 4 分钟的实现时间。它是一段很好的代码,比使用位串来做这类事情要好得多。
  • 在某些时候,您必须弄清楚cobs(delta_rows[row].getByte_List()) 使用了多少时间; bytesarray() 调用将结果完全转换为 C 代码,因此这可能与它的速度一样快。
  • 调用需要 0.111 秒乘以 2159 次调用 = 239 秒或 4 分钟。你是对的。
猜你喜欢
  • 2015-01-30
  • 1970-01-01
  • 2017-11-03
  • 2014-09-29
  • 2014-06-10
  • 2013-08-24
  • 2013-05-29
  • 2014-07-10
  • 1970-01-01
相关资源
最近更新 更多