【发布时间】: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