如何只写 1 个 csv 文件而不是多个 python
How to write only 1 csv file and not multiple with python
我在查找有关通过多天写入同一文件的文档时遇到问题(很抱歉没有使用正确的措辞)。现在它每天打开并写入 1 个 csv 文件(此时 1 天大约有 60 个单独的文件)。相反,我希望所有 60 天的迭代都保存到 1 个文件中。我认为 "a" 代表附加,这意味着写入同一个文件,但我发现这并不准确。我还在最后注释掉了 outfile.close
以为这就是原因。最终目标是每天保存在 1 个文件中,只有 1 header.
脚本:
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='')
outfile
由the_date
决定,所以每天都不一样。
我在查找有关通过多天写入同一文件的文档时遇到问题(很抱歉没有使用正确的措辞)。现在它每天打开并写入 1 个 csv 文件(此时 1 天大约有 60 个单独的文件)。相反,我希望所有 60 天的迭代都保存到 1 个文件中。我认为 "a" 代表附加,这意味着写入同一个文件,但我发现这并不准确。我还在最后注释掉了 outfile.close
以为这就是原因。最终目标是每天保存在 1 个文件中,只有 1 header.
脚本:
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='')
outfile
由the_date
决定,所以每天都不一样。