【问题标题】:While trying to append Python dict to JSON it writes only once在尝试将 Python dict 附加到 JSON 时,它只写入一次
【发布时间】:2018-06-13 15:17:02
【问题描述】:

我正在从事人脸识别项目,并希望将检测到的人脸的日志写入 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 数组,直到我的算法识别出当天的面孔。但是,如前所述,它只写入一次。

【问题讨论】:

  • 代码的 sn-p 从哪里获取函数 write_logs 的值是:logger.write_logs(datetime.strftime(datetime.now(), '%d/%m/ %Y - %H:%M:%S'),str(datetime.now()),unique,str(mean),'default')

标签: python json python-3.x


【解决方案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]

【讨论】:

  • 它有效。但是,输出不是正确的 JSON 格式。我明白了: [ { "time": "13/06/2018 - 23:59:28", "name": "Rajkiran", "accuracy": "91.62468", "direction": "default" } ] [ {“时间”:“13/06/2018 - 23:59:28”,“名称”:“Rakesh”,“准确度”:“74.21411”,“方向”:“默认”}]
  • 但是,我希望它是:[ { "time": "13/06/2018 - 23:59:28", "name": "Rajkiran", "accuracy": "91.62468 ”,“方向”:“默认”},{“时间”:“13/06/2018 - 23:59:28”,“名称”:“Rakesh”,“准确度”:“74.21411”,“方向”: “默认”}]
  • 请看我修改后的答案。
  • 嗨@T.Ray,我现在正在尝试编写一个每天动态创建一个json文件的代码。因此,对您的代码进行了一些更改。但是,它现在只打印一次 json 对象。不确定是否是缩进错误。请看一看。
  • def write_logs(time,date,name,accuracy,direction): entry = {'time':time,'name':name,'accuracy':accuracy,'direction':direction} = './log'+yesterday_str+'.json' log_file = './log'+now1_str+'.json'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2011-10-14
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多