-1

I have a JSON file like this :

{
  "objects": [
    {
      "obj_id": 0,
      "file_name": "xyz"
    },
     {
      "obj_id": 1,
      "file_name": "pqr"
    }
  ]
}

I want to append another dictionary to objects list directly without doing like this:

data_object = {
      "obj_id": 2,
      "file_name": "stu"
    }

# Read the entire file.
with open(fp, 'r') as json_file:
    data = json.load(json_file)

# Update the data read.
credentials = data['objects']
credentials.append(data_object)

# Update the file by rewriting it.
with open(fp, 'w') as json_file:
    json.dump(data, json_file, indent=4, sort_keys=True)

With this I am opening the file each time just to append one single dictionary. Is there a way around this where I can append a dictionary directly to the file without rewriting the contents each time ??

1 Answers1

0

Instead of using w which overwrites, use a which is like append.

with open(fp, 'a') as json_file:
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
  • Even with this I have to load the data every time and then write it to file...Is there a way to append that dictionary directly to file without loading previous data first ?? – NAVNEET HOSMANE Apr 29 '21 at 09:18