关于使用循环读取文件,使用Python将某些东西写入另一个文件中的新行

时间:2015-02-03 18:49:22

标签: python twitter

我正在编写一个Python程序,该程序从一个包含Twitter名称列表的txt.file获取Twitter名称,从Twitter API获取关注者数量,然后将其写入另一个txt.file。 (每个follower_count在我写入的文件中占一行。)

我的程序现在如下,其中包含一些错误,任何人都可以帮我调试它。它没有运行。

我的节目:

import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
CONSUMER_KEY = 'abc'
CONSUMER_SECRET = 'abc'
ACCESS_KEY = 'abc'
ACCESS_SECRET = 'abc'
auth = OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
api = tweepy.API(auth)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
f = open('Twitternames.txt', 'r')
for x in f:
    class TweetListener(StreamListener):
    # A listener handles tweets are the received from the stream.
    #This is a basic listener that just prints received tweets to standard output

    def on_data(self, data):
        print data
        return True

    def on_error(self, status):
        print status
#search
api = tweepy.API(auth)
twitterStream = Stream(auth,TweetListener())
test = api.lookup_users(screen_names=['x'])
for user in test:
    print user.followers_count 
    #print it out and also write it into a file

    f = open('followers_number.txt', 'w')
    string = user.followers_count
    f.write(string/n)

f.close()

我收到以下错误:

File "twittercount.py", line 21 def on_data(self, data): ^ IndentationError: expected an indented block

1 个答案:

答案 0 :(得分:1)

每次f = open('followers_number.txt', 'w')覆盖内容时,在循环外打开文件,如果要保留以前运行的数据,请使用a追加。

with  open('followers_number.txt', 'a') as f: # with close your files automatically
    for user in test:
        print user.followers_count 
        #print it out and also write it into a file
        s = user.followers_count
        f.write(s +"\n") # add a newline with +

如果user.followers_count返回int,则需要使用str(s)

您需要首先声明您的类不在循环中,并且方法应该在类中:

# create class first
class TweetListener(StreamListener):
    # A listener handles tweets are the received from the stream.
    #This is a basic listener that just prints received tweets to standard output

    def on_data(self, data): # indented inside the class
        print(data)
        return True

    def on_error(self, status):
        print(status)

# open both files outside the loop
with open('Twitternames.txt') as f,open('followers_number.txt', 'a') as f1:
    for x in f:   
        #search
        api = tweepy.API(auth)
        twitterStream = Stream(auth,TweetListener())
        test = api.lookup_users(screen_names=[x]) # pass the variable not "x" 
        for user in test:
            print(user.followers_count)
            #print it out and also write it into a file
            s = user.followers_count
            f1.write("{}\n".format(s)) # add a newline with +