Skip to main content
 首页 » 编程设计

python之尝试编写一个每天创建一个新的 json 文件的 python 代码

2024年12月31日9over140

我正在处理人脸识别模型的 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