2012-09-03 15 views
8

पर एक शब्दकोश को संपीड़ित/डिक्रप्रेस करने के लिए zlib और cpickle का उपयोग करके मैं एक 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 

उम्मीद है कि यह सिर्फ है कुछ स्पष्ट (किसी और को) ठीक है कि मैं सिर्फ याद आ रही है। आपकी सहायताके लिए धन्यवाद!

उत्तर

8

त्रुटियों आप प्रयास 3-5 पर हो रही है की जरूरत है, क्योंकि आप pickle.load बजाय pickle.loads उपयोग कर रहे हैं। पूर्व डिकंप्रेशन कॉल से प्राप्त बाइट स्ट्रिंग के बजाए फ़ाइल जैसी ऑब्जेक्ट की अपेक्षा करता है।

यह काम करेगा:

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