Home > Back-end >  Terminal Error I am not able to undertsand in python
Terminal Error I am not able to undertsand in python

Time:12-20

I am trying to download 5000 tweets in a text file as part of an Assignment I have. It is giving me errors, I looked up a solution online and tried fixing it but it is not working well. `

import tweepy

API_KEY = ("AAAAAAAAAAAAAAAAAAAAAIQDkgEAAAAA+5jSmwchB7hT3/Q8jh4EGrpZY/Y=cn2Qvt5oqUP6y03hOywzN7WVUF97kPY27B2pUyeDPleqZvLeAu")

client = tweepy.Client(API_KEY)

query = "covid"
tfile = open("tweets.txt", "w")
response = client.search_recent_tweets(query)
for tweet in tweepy.Paginator(client.search_recent_tweets,
                              query=query,
                              max_results=100).flatten(limit=5000):
  ### WRITE CODE TO SAVE these tweets into a file here.
  tweet = str(tweet)   "/n"
  tfile.write(tweet)

  tfile.close()

Here is the error in Terminal

I tried looking for solutions online and reading threads. It said it was an indentattion error. I did that but it is still showing the same error.

CodePudding user response:

Close the file outside the loop, I think the function Paginator is a generator and it is using the file so you are not able to close it

CodePudding user response:

Use a with statement to ensure that the file is closed, and closed at the proper time, without having to explicitly call tfile.close.

query = "covid"
response = client.search_recent_tweets(query)

with open("tweets.txt", "w") as tfile:

    for tweet in tweepy.Paginator(client.search_recent_tweets,
                                  query=query,
                                  max_results=100).flatten(limit=5000):
        tweet = str(tweet)   "\n"
        tfile.write(tweet)
  • Related