Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将python输出自动保存到csv_Python - Fatal编程技术网

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

如何将python输出自动保存到csv,python,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 whil

下面是我试图将打印状态的结果保存到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”对象不可调用

您只是在打印并丢弃循环的内容;在
for
循环之后<代码>状态。文本将仅包含最后一个状态。请尝试以下方法:

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)

…正如错误消息所说:
status.text
(不带括号)上面几行的用法。表示
status.text
str
。只需按原样使用它,而不是在
for
循环中使用
status.text()
,只需使用
status.text
谢谢,在我删除()后它就可以工作了,但我得到的是空csv。我看不到records@Martin:目前,此代码应该抛出一个错误:
status
对于…中的状态是本地的
,因此请检查缩进并显示
打印(status.text)
。其次,参数
必须是一个
序列
,循环
str
不会产生
序列
。作为一种魅力,我如何删除空格并为每条推文包含“,”?不确定格式到底是什么。如果您试图生成JSON,请使用
append
将推文读入一个列表,然后在循环后将其读入
JSON.dump
即可。我在下面尝试了一下,因为JSON无法通过JSON.dump(status.\u JSON,file,sort\u keys=True,indent=4)工作返回所有似乎未连接到问题代码的Tweets。如果你想不出来,就发布一个新问题,并附上足够的细节。@Martin现在用一个简单的JSON示例查看更新的答案,