gpt4 book ai didi

python - 使用 zlib 和 cPickle 将字典压缩/解压缩到文件

转载 作者:太空狗 更新时间:2023-10-29 20:52:28 29 4
gpt4 key购买 nike

我正在使用 python 将 zlib 压缩和 cPickled 字典写入文件。它似乎可以工作,但是,我不知道如何读回文件。

我包括以下代码,其中包括我尝试过的一些事情(以及相关的错误消息)。我一事无成。

import sys
import cPickle as pickle
import zlib

testDict = { 'entry1':1.0, 'entry2':2.0 }

with open('test.gz', 'wb') as fp:
fp.write(zlib.compress(pickle.dumps(testDict, pickle.HIGHEST_PROTOCOL),9))

attempt = 0

try:
attempt += 1
with open('test.gz', 'rb') as fp:
step1 = zlib.decompress(fp)
successDict = pickle.load(step1)
except Exception, e:
print "Failed attempt:", attempt, e

try:
attempt += 1
with open('test.gz', 'rb').read() as fp:
step1 = zlib.decompress(fp)
successDict = pickle.load(step1)
except Exception, e:
print "Failed attempt:", attempt, e

try:
attempt += 1
with open('test.gz', 'rb') as fp:
step1 = zlib.decompress(fp.read())
successDict = pickle.load(step1)
except Exception, e:
print "Failed attempt:", attempt, e

try:
attempt += 1
with open('test.gz', 'rb') as fp:
d = zlib.decompressobj()
step1 = fp.read()
step2 = d.decompress(step1)
step3 = pickle.load(step2)
except Exception ,e:
print "Failed attempt:", attempt, e

try:
attempt += 1
with open('test.gz', 'rb') as fp:
d = zlib.decompressobj()
step1 = fp.read()
step2 = d.decompress(step1)
step3 = pickle.load(step2)
except Exception ,e:
print "Failed attempt:", attempt, e

我收到以下错误:

Failed attempt: 1 must be string or read-only buffer, not file
Failed attempt: 2 __exit__
Failed attempt: 3 argument must have 'read' and 'readline' attributes
Failed attempt: 4 argument must have 'read' and 'readline' attributes
Failed attempt: 5 argument must have 'read' and 'readline' attributes

希望这只是一些明显的(对其他人来说)修复,我只是错过了。感谢您的帮助!

最佳答案

您在尝试 3-5 时遇到的错误是因为您使用的是 pickle.load 而不是 pickle.loads。前者需要一个类似文件的对象,而不是您从解压缩调用中获得的字节字符串。

这会起作用:

with open('test.gz', 'rb') as fp:
data = zlib.decompress(fp.read())
successDict = pickle.loads(data)

关于python - 使用 zlib 和 cPickle 将字典压缩/解压缩到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12242805/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com