简体   繁体   English

如何只用python写1个csv文件而不是多个

[英]How to write only 1 csv file and not multiple with python

I am having an issue finding documentation on writing to the same file through multiple days(Sorry for not using the proper wordage). 我在查找有关在多天内写入同一文件的文档时遇到问题(很抱歉,未使用正确的单词)。 Right now it opens and writes to 1 csv file per day(which at this time is about 60 seperate files for 1 day). 现在,它每天打开并写入1个csv文件(此时1天约有60个单独的文件)。 Instead I would like all 60 days of iteration to save to 1 file. 相反,我希望将所有60天的迭代保存到1个文件中。 I thought the "a" stood for append which means to write to the same file but that is not accurate I am finding. 我以为“ a”代表追加,表示要写入同一文件,但是我发现这并不准确。 I also commented out the outfile.close at the end thinking that was why. 最后,我还注释掉了outfile.close ,以为这就是为什么。 The end goal is to have everyday saved in 1 file with only 1 header. 最终目标是每天将其保存在只有1个标头的1个文件中。

SCRIPT: 脚本:

import csv
import requests
import datetime
from pprint import pprint
import pendulum

start = pendulum.datetime(2018, 3, 29)
end = pendulum.today()
period = pendulum.period(start, end)

for dt in period.range('days'):
    the_date = dt.format('YYYYMMDD')

    outfile = open('Test_between_dates' + str(the_date) + '.csv',"a",newline='')
    writer = csv.writer(outfile)
    writer.writerow(["time","status",])

    req2 = requests.get('https://api-prod.sprtactn.co/web/v1/scoreboard/mlb?bookIds=21,1,55&date=' + str(the_date) + '') #' + str(the_date) + '
    odd = req2.json()['games']

    for info in odd[0:]:
        time = info['start_time']
        status = info['status']


        print(time, status)

        writer.writerow([time, status])

##    outfile.close()

outfile = open('Test_between_dates' + str(the_date) + '.csv',"a",newline='')

outfilethe_date确定,因此每天都不同。

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

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