2016-02-09 162 views
0

我正在使用Twitter的流媒體API來使用Tweepy提取推文並將它們寫入到json文件中。到目前爲止,我已經成功地提取了推文,並使用file write將它們寫入了一個json文件,但是當我嘗試使用json package時,我收到了以下代碼中提到的錯誤。字典json在循環python

def on_data(self, data): 
    #to convert data to dict format since twitter data is in string format 
    json_data = json.loads(data) 
    try: 
     with open('twitter_data.json','ab') as f: 
       if 'limit' in json_data.keys(): 
        return True 
       else: 
        #This method works 
        #f.write(json.dumps(json_data)+ "\n") 
        #this one does not as it concatenates dict i.e different dict are not separated by a comma 
        json.dump(json_data,f) 
        return True 
    except BaseException as e: 
     print e 
     logging.debug('Error %s',e) 
     return True 

回答

1

你得到正確的數據,但沒有行分隔符...所以自己添加它

import json 
with open('deleteme', 'a') as fp: 
    json.dump('data', fp) 
    fp.write('\n')