简体   繁体   English

如何将我的python输出自动保存到csv

[英]How to save my python output to csv automatically

Below is the code I am trying to save the results I get from my print status to csv or json 下面是我试图将我从打印状态获得的结果保存到csv或json的代码

# Creating the authentication object
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# Setting your access token and secret
auth.set_access_token(access_token, access_token_secret)
# Creating the API object while passing in auth information
api = tweepy.API(auth)
# The Twitter user who we want to get tweets from
name = "mytwitterid"
# Number of tweets to pull
tweetCount = 10

for status in tweepy.Cursor(api.home_timeline).items(10):
    # Process a single status
    print(status.text)

#result = {}

with open('output.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile)
    for row in status.text():
        csvwriter.writerow(row)

This throws error for row in status.text(): TypeError: 'str' object is not callable 这会为status.text()中的行引发错误:TypeError:'str'对象不可调用

You are just printing and discarding the things you loop over; 您只是在打印和丢弃循环的内容。 after the for loop; for循环之后; status.text will only contain the last status. status.text将仅包含最后一个状态。 Try this instead: 尝试以下方法:

with open('output.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile)
    for status in tweepy.Cursor(api.home_timeline).items(10):
        print(status.text)
        csvwriter.writerow([status.text])

If you want to collect the results into a list variable which you then dump out as a single JSON file, use append in the loop. 如果要将结果收集到列表变量中,然后将其作为单个JSON文件转储出去,请在循环中使用append

results = []  # start with an empty list
for status in tweepy.Cursor(api.home_timeline).items(10):
    #print(status.text)
    results.append(status.text)

# Now dump results as JSON
with open('results.json', 'w') as outputfile:
    json.dump(results, outputfile)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM