假设说我有字节格式的键和值。我需要写入此信息进行归档,然后将其读回以进行重放。最简单的方法是将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
我无法找到解决此问题的方法。请帮我解决问题。
答案 0 :(得分:1)
您可能只是pickle.dump()
(key, value)
元组。并使用pickle.load()
阅读它。
答案 1 :(得分:0)
您不需要ctypes
或struct
。只需以二进制模式打开文件,然后您就可以编写&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
的hexdump00000000 01 02 03 04 05 06 07 08 f8 f9 fa fb fc fd fe ff |................|
00000010