簡體   English   中英

如何只用python寫1個csv文件而不是多個

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

我在查找有關在多天內寫入同一文件的文檔時遇到問題(很抱歉,未使用正確的單詞)。 現在,它每天打開並寫入1個csv文件(此時1天約有60個單獨的文件)。 相反,我希望將所有60天的迭代保存到1個文件中。 我以為“ a”代表追加,表示要寫入同一文件,但是我發現這並不准確。 最后,我還注釋掉了outfile.close ,以為這就是為什么。 最終目標是每天將其保存在只有1個標頭的1個文件中。

腳本:

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