Я работаю над журналами 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: при попытке добавить Python dict в JSON он записывает только один раз
Если вы собираетесь создавать новый файл журнала каждый день в полночь, вам не нужно сравнивать даты. Если будет полночь, то новая дата будет ВСЕГДА старше старой даты (т.е. Вчера). Поэтому сравнение не имеет смысла. Если это новый день, write_logs
автоматически создаст новый файл журнала. Теперь, если вам нужно создать новый файл журнала (в полночь), независимо от того, есть ли у вас запись для записи, вы можете написать функцию-обертку для обработки:
def update_logs(args=None):
# If no entry is passed, create new log file
if not args:
log_file = './log'+now_str+'.json'
if not os.path.exists(log_file):
# Create file with JSON enclosures
with open(log_file, 'w') as f:
json.dump([], f)
else:
# A new entry is passed, update existing log file
write_logs(*args)
def write_logs(time, date, name, accuracy, direction):
entry = {'time': time,
'name': name,
'accuracy': accuracy,
'direction': direction}
log_file = './log'+now_str+'.json'
if not os.path.exists(log_file):
# Create file with JSON enclosures
with open(log_file, '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, 'w') as f:
json.dump(data, f, indent=3)
return [entry]
# Example records
entries = [("18/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
("18/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default')]
# Case 1: Log file already exists, update it
now = datetime.strftime(datetime.now(), '%Y%m%d')
now_str = str(now)
for entry in entries:
update_logs(entry)
# Case 2: Midnight, no entries, create a new empty log file
now = datetime.strftime(datetime.now() + timedelta(days=1), '%Y%m%d')
now_str = str(now)
update_logs()
# Case 3: Midnight, with entries to write
now = datetime.strftime(datetime.now() + timedelta(days=1), '%Y%m%d')
now_str = str(now)
for entry in entries:
update_logs(entry)
Вызов update_logs
будет обрабатывать все для вас.
Измените свой mode='w'
на mode='a'
w
перезаписывает любой существующий файлМного полезной информации здесь: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python