2011-03-13 48 views
1

我正在使用cPickle將字典對象存儲到文件中,並且無法獲取除第一個以外的任何其他條目。最初文件tweets.pkl爲空,並且EOFError被引發。我相信它與它有關。由於使用cPickle只返回文件中的第一個條目

#!/usr/bin/env python                                   

from urllib import urlencode, urlopen 
from simplejson import loads 
from hashlib import md5 
from collections import defaultdict 
import json 
import cPickle as pickle 

def fetch_tweets(new_feeds): 
    dic = json.loads(new_feeds) 
    feeds_file = open('tweets.pkl','r+b') 
    try: 
     feeds = pickle.load(feeds_file) 
    except EOFError: 
    #THIS IS BAD 
     feeds = defaultdict() 
    feeds_file.close() 
    # RETURNS ONLY THE FIRST FEED ENTRY            
    for i in feeds.iteritems(): 
     print str(i) 

    for i in dic['results']: 
     hash = computeHash(i['text']) 

     if hash not in feeds: 
      appendfeed(hash, i, 'tweets.pkl') 


def appendfeed(hash, new_feed, file): 
    feed = defaultdict() 
    file = open(file, 'a+b') 
    feed[hash] = new_feed 
    pickle.dump(feed, file) 
    file.close() 

def computeHash(data): 
    h = md5(data.encode('utf-8')) 
    return h.hexdigest() 

回答

2

你構建一個新字典(feed = defaultdict())每次appendfeed被調用,從而使新字典失去了以前的所有引用。然後,您將新的(單項)字典添加到文件中。

如果你想多個獨立的呼叫恢復dump這樣,那麼你就需要多個匹配調用loadunpickle,我相信。然後,每個呼叫應該分別返回一個單獨的dict

如果您想要存儲一個帶有多個密鑰的字典,請丟失append模式,並在需要保存時重新整理字典。如果您想要更高效地存儲簡單映射,請參閱shelveshove

+0

謝謝。我不知道擱置。這是一種更有效的方式。 – ajmartin 2011-03-13 01:31:10

+0

很高興幫助。從山景南部的問候:) – phooji 2011-03-13 02:58:45

相關問題