我正在处理我的人脸识别模型的 json 日志,我的任务是编写每天动态创建新文件的代码。我有一个代码,但不确定为什么它只写入第一个日志。我希望只要我的相机继续识别面孔,它就会不断附加。
这是我的代码:
from datetime import datetime,timedelta
import os
from pprint import pprint
import json
yesterday = datetime.now() - timedelta(days=1)
yesterday1 = datetime.strftime(yesterday, '%Y%m%d')
yesterday_str = str(yesterday1)
now1 = datetime.strftime(datetime.now(), '%Y%m%d')
now1_str = str(now1)
def write_logs(time,date,name,accuracy,direction):
entry = {'time':time,'name':name,'accuracy':accuracy,'direction':direction}
yesterday_log_file = './log'+yesterday_str+'.json'
log_file = './log'+now1_str+'.json'
if os.path.exists(yesterday_log_file):
with open(yesterday_log_file) as f:
Date = json.load(f)
Date1 = (Date[-1])
Comparision_Date = Date1['time']
a = datetime.strptime(Comparision_Date[:10],'%d/%m/%Y')
print(a)
now = datetime.strptime(datetime.now(),'%d/%m/%Y')
if a == now:
with open(yesterday_log_file, 'r') as r:
data = json.load(r)
data.append(entry)
with open(log_file, mode='w') as f:
json.dump(data, f, indent=3)
if a < now:
# Create file with JSON enclosures
with open(log_file, mode='w') as f:
json.dump([], f)
# The file already exists, load and update it
with open(log_file, 'r') as r:
data = json.load(r)
data.append(entry)
# Write out updated data
with open(log_file, mode='w') as f:
json.dump(data, f, indent=3)
else:
# Create file with JSON enclosures
with open(log_file, mode='w') as f:
json.dump([], f)
# The file already exists, load and update it
with open(log_file, 'r') as r:
data = json.load(r)
data.append(entry)
# Write out updated data
with open(log_file, mode='w') as f:
json.dump(data, f, indent=3)
return [entry]
但是,让我告诉你,它适用于单个 if 语句,正如 @T.Ray 所提到的:While trying to append Python dict to JSON it writes only once
最佳答案
将 mode='w'
更改为 mode='a'
w
覆盖任何现有文件a
只是附加到现有文件上(如果不存在则创建一个文件)
这里有很多好信息: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
关于python - 尝试编写每天创建一个新的 json 文件的 python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920051/