在尝试将Python dict附加到JSON时,它只编写一次

问题描述 投票:0回答:1

我正在进行面部识别项目,并希望将检测到的面部日志写入JSON文件。我使用以下代码。

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数组,直到我的算法识别当天的面部为止。但是,如前所述,它只写一次。

python json python-3.x
1个回答
1
投票

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

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

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]
© www.soinside.com 2019 - 2024. All rights reserved.