Python 保存输出时的问题

0 投票
1 回答
578 浏览
提问于 2025-04-30 21:10

作为一个刚接触Python的新手,我遇到了一个问题。我的代码本来是想把Twitter搜索的结果打印到屏幕上,但我希望能把这些结果保存到一个文件里(最好是用管道符分隔的格式,但我还不知道怎么做)。不过,下面的代码运行得还不错,但就是没有创建Output.txt这个文件。它之前创建过一次,但之后就再也没有了。我是在Mac OS上运行这个代码的,每次都用Ctrl+C结束代码(因为我还不知道怎么修改代码,只返回特定数量的推文)。我觉得问题可能和Flush有关,但我尝试了这个帖子里的选项:Flush问题,结果都没有奏效(除非我做错了什么,这种可能性很大...)

import tweepy
import json
import sys

# Authentication details. To  obtain these visit dev.twitter.com
consumer_key = 'xxxxxx'
consumer_secret = 'xxxxx'
access_token = 'xxxxx-xxxx'
access_token_secret = 'xxxxxxxx'

# This is the listener, resposible for receiving data
class StdOutListener(tweepy.StreamListener):
    def on_data(self, data):
        # Twitter returns data in JSON format - we need to decode it first
        decoded = json.loads(data)

        # Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
        print '@%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
        print ''
        return True

    def on_error(self, status):
        print status

if __name__ == '__main__':
    l = StdOutListener()
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    print "Showing all new tweets for #Microsoft"

    stream = tweepy.Stream(auth, l)
    stream.filter(track=['Microsoft'])

    sys.stdout = open('Output.txt', 'w')
暂无标签

1 个回答

2

我觉得你最好直接修改一下 StdOutListener,让它直接写入文件。把 sys.stdout 指向一个文件有点奇怪。这样的话,你可以用 print 来输出调试信息。另外要注意,文件模式 "w" 在打开文件时会把文件内容清空。

class TweepyFileListener(tweepy.StreamListener):
    def on_data(self, data):
        print "on_data called"
        # Twitter returns data in JSON format - we need to decode it first
        decoded = json.loads(data)
        msg = '@%s: %s\n' % (
            decoded['user']['screen_name'], 
            decoded['text'].encode('ascii', 'ignore'))

        #you should really open the file in __init__
        #You should also use a RotatingFileHandler or this guy will get massive
        with open("Output.txt", "a") as tweet_log:
            print "Received: %s\n" % msg
            tweet_log.write(msg)

撰写回答