首页 > 解决方案 > 检查 .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中做到这一点?请帮忙。

标签: pythonpython-3.x

解决方案


 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
    

推荐阅读