我有这样一个元组(请注意,第一个元素可以是任意大小的(大但不是非常大,即。2**12 -1是可以的),第二次将始终在0,255范围内)。
t = [(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), ...]我想将这些数字作为字节存储在文件系统中(用于压缩)。这意味着我还希望稍后使用这些位来恢复元组。还请注意,这是使用大端点的一个要求。
for idx, v in compressed:
if v:
f.write(struct.pack(">I", idx))
f.write(struct.pack(">I", v)) 然而,当我试图得到数字时,就像这样:
with open(filepath, 'rb') as file:
data = file.read(4)
nums = []
while data:
num = struct.unpack(">I", data)[0]
print(num)
data = file.read(4)
nums.append(num) 我没有得到以上的数字(我是一些数字,但后来它被搞砸了,可能是因为比特填充)。
如何与比特填充保持一致?如何使用struct.pack('>I, ...)添加一些以后可以可靠获得的内容?
更新:
对于下面的元组[(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246) ...]
我用我的方法得到以下数字:
[0, 137, 0, 80, 0, 78, 0, 71, 0, 13, 0, 10, 0, 26, 9, 13, 0, 73, 0, 72, 0, 68, 0, 82, 0, 1, 0, 44, 15, 1, 17, 8, 0, 2, 0, 246 ...]
看,在(6,0)开始发散。在那之前没问题。但它能自我纠正??在9,13岁,并继续做得很好。
发布于 2019-10-04 22:23:29
你的代码似乎运行良好。但是,这里确实有以下一行:
if v:对于其中一些元组,v将是False,其中第二个元素是0,它不会被写入文件,因此在读取该文件时不会看到它们。
此外,由于您是以成对方式编写元素,所以可以使用>II作为您的格式:
from struct import pack, unpack, calcsize
original = [(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246)]
filename = "test.txt"
fileformat = ">II"
with open(filename, "wb") as fp:
for element in original:
fp.write(pack(fileformat, *element))
with open(filename, "rb") as fp:
elements = iter(lambda: fp.read(calcsize(fileformat)), b"")
readback = [unpack(fileformat, element) for element in elements]
print(readback == original)发布于 2019-10-04 22:25:55
鉴于以下投入:
compressed = [(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246)]尝试使用以下代码来压缩数据:
import struct
with open('file.dat', 'wb') as f:
for idx, v in compressed:
f.write(struct.pack(">I", idx))
f.write(struct.pack(">I", v)) 这段代码用于阅读:
with open('file.dat', 'rb') as f:
data = f.read(4)
nums = []
while data:
idx = struct.unpack(">I", data)[0]
data = f.read(4)
v = struct.unpack(">I", data)[0]
data = f.read(4)
nums.append((idx,v)) nums包含:
[(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246)]这与输入相同,实际上nums == compressed给出了True。
https://stackoverflow.com/questions/58243526
复制相似问题