我想用python创建一个太阳能数据数据库,存储在.csv文件中,为此,我需要在while True循环中写入.csv文件。但如果循环从未结束,它就不会将数据写入CSV文件,但如果我在while循环结束时对其进行限制,它就会写入文件。所以我需要找到一种方法来写数据,同时让循环永远继续下去。
到目前为止我的代码:
#imports
import csv
import json
import requests
import datetime
import time as tim
#varables
x=0
y=0
date=0
date2=0
#loop
with open('recent_flares.csv', 'a+') as rf:
#write the header
flaresw = csv.writer(rf, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
flaresw.writerow(['date and time', 'flare size', 'begin time', 'end time', 'current xray flux'])
while y<10:
#request the json data
headers = {'User-Agent': 'python program grabbing data from the API'}
response = requests.get("https://services.swpc.noaa.gov/json/goes/primary/xray-flares-latest.json", headers=headers)
flare = json.loads(response.text)
#sort the json data
flares = flare[0]
time = flares['time_tag']
#if it hasnt do nothing
if date == time:
date=time
#if it has updated write the current data to the file
if date != time:
stuff = [flares['time_tag'], ]
flaresw.writerow(stuff)
tim.sleep(1)
print("debug")
print(stuff)
#y=y+1 loop limiter
您可以使用flush:清除文件的内部缓冲区
rf.flush()