python - 检查 .json 文件是否为空,然后从 python 的目录中删除它
问题描述
start_date = datetime.date(2020, 7, 1)
end_date = datetime.date(2020, 8, 9)
delta = datetime.timedelta(days=1)
while start_date<= end_date:
url = f'https://newweb.nepalstock.com.np/api/nots/nepse-data/today-price?sort=symbol&size=500&businessDate={start_date}'
with urllib.request.urlopen(url) as url:
data=json.loads(url.read().decode())
contents = data['content']
out_file = open(str(start_date) +".json", "w")
json.dump(contents, out_file, indent = 6)
out_file.close()
现在,我的目录中有许多 .json 文件。其中一些是空的[ ](带有两个括号)。我想检查文件是否为空并将其删除。我怎么能在python中做到这一点?请帮忙。
解决方案
import requests
import datetime
import json
start_date = datetime.date(2020, 7, 1)
end_date = datetime.date(2020, 8, 9)
url = f'https://newweb.nepalstock.com.np/api/nots/nepse-data/today-price?
sort=symbol&size=5&businessDate={start_date}'
response = requests.get(url)
data = response.json()
if data:
with open(str(start_date) +'.json', 'w') as json_file:
json.dump(data, json_file)
start_date += delta
推荐阅读
- angular - 角度构建中的 AOT 模式添加 `fr.` 或 `en.` 作为 transloco 中翻译键的前缀
- c - 如何使用 MCC 将 I2C 与 XC16 结合使用 - Microchip
- regex - 正则表达式匹配列中的 2 个单词
- jquery - 为什么我的轮播滑块中的图像没有响应?
- java - 如何解析 Java 中的任何 URL/URI?
- apache-kafka - 如果 kafka connect 的 debezium 源连接器无法生成到 kafka 怎么办
- forms - 如何在 SwiftUI 中的表单底部添加空格?
- python-3.x - 如何从 Python 生成的动态循环中删除空值?
- python - 如何获取dict列表的索引并将dict添加到每个索引?
- symfony - 在 symfony 中创建另一个实例的空副本