使用cPickle只返回文件中的第一个条目
我正在使用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()