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

时间:2019-03-21 17:00:43

标签: python

下面是我要保存从打印状态获得的结果到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)

这会为status.text()中的行引发错误: TypeError:“ str”对象不可调用

1 个答案:

答案 0 :(得分:1)

您只是打印并丢弃循环的内容;在for循环之后; status.text仅包含最后一个状态。尝试以下方法:

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])

如果要将结果收集到列表变量中,然后将其作为单个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)