Tweety写入文本文件

时间:2018-04-21 00:53:44

标签: python python-3.x

我正在学习tweepy库来访问twitter api。我有一个带有一些初步数据的csv文件(例如tweet_id),我将其拉入数据帧。我需要使用这些数据来使用tweepy来获取更多数据。

我正在尝试将该数据写入文本文件,然后创建一个新的数据框。在过去的几个晚上我一直在尝试不同的事情,我不明白为什么这不是将数据写入文本文件。我将所有必要的令牌存储在变量中。

auth = tweepy.OAuthHandler(Consumer_Key, Consumer_Secret)
auth.set_access_token(Access_Token, Access_Secret)
tweetapi = tweepy.API(auth, 
wait_on_rate_limit=True,wait_on_rate_limit_notify=True)
#writing text file
txtfile = open("jsontweet3.txt", "a")
txtfile.write('tweet_id retweet_count favorite_count''\n')
#pulling tweet info
for tweet_id in fdf.tweet_id:
  try:
    twitinfo = tweetapi.get_status(str(tweet_id),tweet_mode='extended')
    retweets = twitinfo.retweet_count
    favorites = twitinfo.favorite_count
    txtfile.write(twitinfo+' '+str(retweets)+' '+str(favorites)+'\n')

txtfile.close()

我非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

我不清楚错误是什么,可能只是因为try条款。

以下是一些我希望可能派上用场的建议:

  • try条款:

    • 需要except子句,否则会引发SyntaxError。如果你不想要except: pass之外的任何内容,但你真的不应该使用它:Why is except pass a bad programming practice
    • 始终尝试将try内的代码限制为尽可能最小,理想情况下只限于可能失败的代码行
  • 读/写文件:

    • 通常最好的做法是使用with(称为上下文管理器),它基本上为您打开和关闭,但是以更安全的方式,因为如果with内的任何内容出错它仍然会关闭文件。见下面的例子:
with open('file.txt', 'a') as f:
    f.write('foobar')

使用这些可能的代码重写如下:

auth = tweepy.OAuthHandler(Consumer_Key, Consumer_Secret)
auth.set_access_token(Access_Token, Access_Secret)
tweetapi = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)


failed_tweets = []  # keep track of the tweets that fail

#writing text file
with open("jsontweet3.txt", "a") as txtfile:
    txtfile.write('tweet_id retweet_count favorite_count \n')

    #pulling tweet info
    for tweet_id in fdf.tweet_id:
        try:
            twitinfo = tweetapi.get_status(str(tweet_id), tweet_mode='extended')

        except:
            # Not able to get tweet --> add to failed_tweets list
            failed_tweets.append(tweet_id)

        else:
            # only gets executed if the try clause did not fail         
            retweets = twitinfo.retweet_count
            favorites = twitinfo.favorite_count
            txtfile.write(str(twitinfo)+' '+str(retweets)+' '+str(favorites)+'\n')