尝试将Python dict附加到JSON时,它仅写入一次 [英] While trying to append Python dict to JSON it writes only once

查看:142
本文介绍了尝试将Python dict附加到JSON时,它仅写入一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行人脸识别项目,并希望将检测到的人脸日志记录到JSON文件中.我正在使用以下代码.

I am working on a Face Recognition project and want to write logs of detected faces, into a JSON file. I am using the following code.

import os
import json
from datetime import datetime,date

now = datetime.strftime(datetime.now(), '%Y%m%d')
now_str = str(now)

def write_logs(time,date,name,accuracy,direction):
    a = []
    entry = {'time':time,'name':name,'accuracy':accuracy,'direction':direction}
    if not os.path.isfile('./log'+now_str+'.json'):
        a.append(entry)
        with open('./log'+now_str+'.json', mode='a+') as f:
            json.dump(a,f, indent=3)
    return a

输出为:

[
   {
      "time": "13/06/2018 - 20:39:07",
      "name": "Rajkiran",
      "accuracy": "97.22941",
      "direction": "default"
   }
] 

但是,我期望的是:

[
   {
      "time": "13/06/2018 - 20:39:07",
      "name": "Rajkiran",
      "accuracy": "97.22941",
      "direction": "default"
   },
{
      "time": "13/06/2018 - 20:39:07",
      "name": "Rajkiran",
      "accuracy": "97.22941",
      "direction": "default"
   },
{
      "time": "13/06/2018 - 20:39:07",
      "name": "Rajkiran",
      "accuracy": "97.22941",
      "direction": "default"
   }
]

应该连续添加JSON数组,直到我的算法识别出当天的面孔为止.但是,如前所述,它只写入一次.

The JSON arrays should be appended continuously, till the time my algorithm recognizes faces for the day. However, as mentioned earlier, it writes only once.

推荐答案

@RAJKIRAN VELDUR:问题是您的if语句.根据您的代码,文件一旦存在,就无法追加.我相信您只需要从if语句中删除not,或完全删除if语句.根据您要完成的任务,您实际上并不需要它.

@RAJKIRAN VELDUR: The problem is your if-statement. According to your code, once the file exists, you cannot append to it. I believe you just need to remove not from your if-statement, or remove the if-statement altogether. Based on what you're trying to accomplish, you don't actually need it.

编辑:json模块不允许您以所需的方式附加到文件.最直接的方法是每次您要追加时加载和更新数据.像这样:

The json module doesn't allow you to append to a file in the way that you want. The most straightforward approach will be to load and update the data each time you want to append. Like so:

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, 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]

这篇关于尝试将Python dict附加到JSON时,它仅写入一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆