简体   繁体   中英

While trying to append Python dict to JSON it writes only once

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

The output is:

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

However, what I was expecting is:

[
   {
      "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"
   }
]

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: 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.

EDIT: 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM