Suppose I need to have a database file consisting of a list of dictionaries:
file:
[
{"name":"Joe","data":[1,2,3,4,5]},
{ ... },
...
]
I need to have a function that receives a list of dictionaries as shown above and appends it to the file. Is there any way to achieve that, say using json (or any other method), without loading the file?
EDIT1: Note: What I need, is to append new dictionaries to an already existing file on the disc.
If it is required to keep the file being valid json, it can be done as follows:
This opens the file for both reading and writing. Then, it goes to the end of the file (zero bytes from the end) to find out the file end's position (relatively to the beginning of the file) and goes last one byte back, which in a json file is expected to represent character
]
. In the end, it appends a new dictionary to the structure, overriding the last character of the file and keeping it to be valid json. It does not read the file into the memory. Tested with both ANSI and utf-8 encoded files in Python 3.4.3 with small and huge (5 GB) dummy files.A variation, if you also have
os
module imported:It defines the byte length of the file to go to the position of one byte less (as in the previous example).
If you are looking to not actually load the file, going about this with
json
is not really the right approach. You could use a memory mapped file… and never actually load the file to memory -- amemmap
array can open the file and build an array "on-disk" without loading anything into memory.Create a memory-mapped array of dicts:
Now read the array, without loading the file:
The contents of the file are loaded into memory when the list is created, but that's not required -- you can work with the array on-disk without loading it.
It takes a negligible amount of time (e.g. nanoseconds) to create a memory-mapped array that can index a file regardless of size (e.g. 100 GB) of the file.
Using the same approach as user3500511...
Suppose we have two lists of dictionaries (dicts, dicts2). The dicts are converted to json formatted strings. Dicts is saved to a new file - test.json. Test.json is reopened and the string objects are formatted with the proper delimiters. With the reformatted objects, dict2 can be appended and the file still maintains the proper structure for a JSON object.
You can use json to dump the dicts, one per line. Now each line is a single json dict that you've written. You loose the outer list, but you can add records with a simple append to the existing file.
The list can be assembled later
The file looks like