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

标签 python json python-3.x

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

相关文章:

Python 写入 (xlwt) 到现有 Excel 工作表、删除图表和格式

python - python pandas导入excel文件出错

c# - 如何使用 JSON.Net 将 System.Drawing.Size 反序列化/序列化为对象?

python - 顺时针对ndarray进行排序的Numpyic方法?

python - 继承 `int` 的类获得奇怪的幽灵般的变量赋值

python - 我的 if 和 elif 语句没有执行

java - Jackson解析Json错误,转换为java.time.LocalDateTime时发生InvalidDefinitionException

javascript - 从 jquery 表单数据中删除 json 对象

python - 异常 "There is no current event loop in thread ' MainThread'“在运行新循环时

python - 在 Pandas 中创建层次结构列