pythonvariablestwittersavetwython

Twython - Saving Tweet IDs in a Text File


I am fairly new to Python, but have been enjoying it so far. I've been trying to write a code using Twython that saves the Tweet IDs of all the tweets that match my search query as variables in a file.

I find that I can print all of the IDs that pertain to my search query with the following code:

import sys
from twython import Twython

APP_KEY='XXXXXXXX'
APP_SECRET='XXXXXXXX'
OAUTH_TOKEN='XXXXXXXX'
OAUTH_TOKEN_SECRET='XXXXXXXX'

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

I = 12345678910

result = twitter.search(q='WhateverImLooking4', since_id=str(I), count=100)


for item in result['statuses']:
       print(item['id_str'].encode('ascii', 'ignore'))

Now, when I change the last two lines to this instead:

for item in result['statuses']:    
    f = open('Results.txt','w')
    f.write(item['id_str'].encode('ascii', 'ignore'))
    f.close()

It will save only the smallest ID number to a text file. I'd like to be able to save all the results to a file AND ideally as variables ready to be used in another python code.

Hopefully this all makes sense!

Thanks!!


Solution

  • This is because you are opening the file and writing over the previous ID each time you execute your for loop.

    Try opening the file before the for loop:

    f = open('Results.txt','w')
    for item in result['statuses']:    
        f.write(item['id_str'].encode('ascii', 'ignore') + "\n")
    
    f.close()