python无限循环停止写入文件
我正在从api服务器下载动态数据,并通过python中的无休止循环将其写入文件。不管出于什么原因,程序在几千行之后停止写入文件,而程序似乎正在运行。我不确定问题出在哪里。程序没有给出错误,即不是API服务器拒绝响应。重新启动后,它将按计划继续运行。我正在使用python 3.6和win10 代码的简化版本如下所示:python无限循环停止写入文件,python,infinite-loop,Python,Infinite Loop,我正在从api服务器下载动态数据,并通过python中的无休止循环将其写入文件。不管出于什么原因,程序在几千行之后停止写入文件,而程序似乎正在运行。我不确定问题出在哪里。程序没有给出错误,即不是API服务器拒绝响应。重新启动后,它将按计划继续运行。我正在使用python 3.6和win10 代码的简化版本如下所示: import requests, json, time while True: try: r = requests.get('https://someapis
import requests, json, time
while True:
try:
r = requests.get('https://someapiserver.com/data/')
line = r.json()
with open('file.txt', 'a') as f:
f.write(line)
time.sleep(5)
except:
print('error')
time.sleep(10)
尝试先打开文件并保持锁定,如下所示:
import requests, json, time
f = open('file.txt', 'a')
while True:
try:
r = requests.get('https://someapiserver.com/data/')
line = r.json()
f.write(line)
f.flush()
time.sleep(5)
except:
print('error')
time.sleep(10)
f.close() # remember to close the file
这个解决方案很难看,但也行