如何在python中打包两个字节数组并从文件中读/读

时间:2016-12-10 08:38:44

标签: python struct memoryview

假设说我有字节格式的键和值。我需要写入此信息进行归档,然后将其读回以进行重放。最简单的方法是将len(key)| key | len(value)|值写入等等。我试图使用python memoryview和struct编写这个逻辑。

struct模块中的

pack_into只接受输入为整数。

import sys
from struct import *
from ctypes import *

buf = create_string_buffer(16)
key = b'<some data in hex>'
value = b'<some data in hex>
pack_into("@QQ",buf,0,key,value)
struct.error: required argument is not an integer

我无法找到解决此问题的方法。请帮我解决问题。

2 个答案:

答案 0 :(得分:1)

您可能只是pickle.dump() (key, value)元组。并使用pickle.load()阅读它。

答案 1 :(得分:0)

您不需要ctypesstruct。只需以二进制模式打开文件,然后您就可以编写&amp;直接读取字节。

演示:

key = b'\x01\x02\x03\x04\x05\x06\x07\x08'
val = b'\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
print(key, val)

fname = 'test.dat'
with open(fname, 'wb') as f:
    f.write(key + val)

with open(fname, 'rb') as f:
    key = f.read(8)
    val = f.read(8)

print(key, val)

<强>输出

b'\x01\x02\x03\x04\x05\x06\x07\x08' b'\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
b'\x01\x02\x03\x04\x05\x06\x07\x08' b'\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'  

test.dat

的hexdump
00000000  01 02 03 04 05 06 07 08  f8 f9 fa fb fc fd fe ff  |................|
00000010