9

私は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

うまくいけば、これは私が見逃している明らかな(他の誰かにとっての)修正です。ご協力いただきありがとうございます!

4

2 に答える 2

8

試行 3 ~ 5 で発生するエラーは、pickle.load代わりに を使用しているためですpickle.loads。前者は、解凍呼び出しから取得するバイト文字列ではなく、ファイルのようなオブジェクトを想定しています。

これはうまくいきます:

with open('test.gz', 'rb') as fp:
    data = zlib.decompress(fp.read())
    successDict = pickle.loads(data)
于 2012-09-03T06:26:52.037 に答える
3

pickle.load*s* pickle マニュアルによると、 http://docs.python.org/release/2.5/lib/node317.htmlを使用する必要があります(明らかに「*」を削除してください)

于 2012-09-03T06:23:30.567 に答える