我正在使用cPickle将字典对象存储到文件中,并且除了第一个之外不能获得任何其他条目。最初文件tweets.pkl
为空,并引发EOFError
。我相信它与它有关。谢谢
#!/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()