我正在使用Python编写一个zlib压缩和cPickle序列化过的字典,它似乎可以正常工作,但是我不知道如何读取文件。
以下代码包括了我尝试过的几种方法(以及相关的错误信息),但是我一无所获。
我得到了以下错误提示:
以下代码包括了我尝试过的几种方法(以及相关的错误信息),但是我一无所获。
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
希望这只是一个显而易见的问题(对于别人而言),我可能只是遗漏了一些东西。感谢您的帮助!