我有一个json文件,我想制作一个计数器,每次一天(天=最后一天-今天)(最后一天是计数器停止的那一天,这一天将为0)是0,那么我应该删除特定的我成功地制作了计数器,但我不知道如何让它从 json 文件中删除特定的字典。也许如果我可以读取光标所在位置并使用字典计数 count day = 0 那么一切都会更好。
这里是json文件的类型:
[
{
"Name": "bla",
"Lastname": "ftr",
"date": "20/12/2023"
},
{
"Name": "dfas",
"Lastname": "fsae",
"date": "18/12/2023"
},
{
"Name": "john",
"Lastname": "rapper",
"date": "18/11/2023"
}
]
import time
from datetime import datetime
import json
import time
def countdown(stop):
while True:
difference = stop - datetime.now()
if difference.days == 0:
print("Good bye!")
break
print("The count is: " + str(difference.days) + " day(s)")
break
def handling():
with open('tst.json') as f:
data = json.load(f)
for i in range(len(data)):
date = data[i]["date"]
i = i + 1
x = (datetime.now() - datetime.strptime(date, '%d/%m/%Y')).days
print(x)
if x == 0:
print("Here i want to remove the dictionary that counts day = 0)
我也尝试过,但没有任何反应:
import json
with open('tst.json') as fin:
your_structure = json.load(fin)
for value in your_structure:
p = value.pop("date", None)
print(p)
print("all done")
功能
handling
需要一些改变。代码未经测试,所以要小心:
def handling():
with open('tst.json') as f:
data = json.load(f)
data_copy = data[:] # Don't iterate over data while changing it, use a copy
for i in range(len(data)):
date = data_copy[i]["date"]
# i = i + 1 # Not useful
x = (datetime.now() - datetime.strptime(date, '%d/%m/%Y')).days
print(x)
if x == 0:
del data[i]
# data was modified, now it must be saved
with open('tst.json', 'w') as f:
json.dump(data, f)