我正在使用 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
希望这只是我缺少的一些明显(对其他人)的修复。谢谢你的帮助!