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

9
我正在使用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

希望这只是一个显而易见的问题(对于别人而言),我可能只是遗漏了一些东西。感谢您的帮助!

2个回答

8
您在第3到5次尝试中遇到的错误是因为您使用了pickle.load而不是pickle.loads。前者需要类似文件的对象,而不是从解压缩调用中获取的字节字符串。
以下代码将起作用:
with open('test.gz', 'rb') as fp:
    data = zlib.decompress(fp.read())
    successDict = pickle.loads(data)

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接