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

时间:2018-06-13 15:17:02

标签: python json python-3.x

我正在开发一个面部识别项目,并希望将检测到的面部日志写入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数组,直到我的算法识别当天的面部为止。但是,如前所述,它只写一次。

1 个答案:

答案 0 :(得分: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]