关于使用循环读取文件、处理并使用Python将某些内容写入另一个文件的新行

2024-04-20 10:29:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个Python程序,它从一个txt文件它包含Twitter名称的列表,从twitterapi获取关注者的数量,然后将其写入另一个txt文件. (每个follower\u计数在我要写入的文件中占用一行。)

我的程序现在如下,其中包含一些错误,谁能帮我调试它。它不跑了。你知道吗

我的程序:

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


Tags: 文件keyfromimport程序txtauthapi
1条回答
网友
1楼 · 发布于 2024-04-20 10:29:43

每次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 +

相关问题 更多 >