2012-09-03 197 views
8

我正在使用python將zlib壓縮和cPickled字典寫入文件。它似乎工作,但是,我不知道如何重新讀取文件。使用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 

但願這只是一些顯而易見的(給別人)解決這個問題,我只是缺少。謝謝你的幫助!

回答

8

你正在嘗試次數3-5的錯誤是因爲您使用pickle.load代替pickle.loads。前者需要一個類似文件的對象,而不是從解壓縮調用中獲得的字節字符串。

這將工作:

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