简体   繁体   中英

Saving Data retrieved from Twitter utilizing Python to a text file?

Hello all I am currently working on doing some research and was utilizing the twitter api to collect information. I wrote some code to query for specific tweets in python and would like to save the results to a text file, yet my code is only returning the last tweet of the tweets returned can anyone tell me how I may correct this and what's wrong? The following is a sample of my code in Python only saving the last tweet instead of all of the returned tweets:

u = urllib2.urlopen('http://search.twitter.com/search.json?geocode=29.762778,-95.383056,10.0mi&page=1&rpp=10')
datares = json.load(u)
pprint.pprint(datares)
for tweet in datares['results']:
  print tweet['text']
  archive=tweet['text']
  unicodedata.normalize('NFKD', archive).encode('ascii','ignore')
  with codecs.open('HTXtweets.txt',mode='w', encoding='utf-8',errors='replace') as cache:
    cache.write(archive)
    cache.closed

You're opening the file in each iteration of the loop through the results. This recreates it from scratch each time.

You should open it before the loop - you don't need to close it at the end, as that will happen automatically when the with statement finishes.

The reason for this is that you open the file for writing in each iteration. This will replace existing content in the file. Try using the flag 'a' (as in append) instead when opening the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM