简体   繁体   中英

do both json.load() and json.dump() at once in Python

I am trying to do something like this which uses reading, appending and writing at the same time.

with open("data.json", mode="a+") as file:
            # 1.Reading old data
            data = json.load(file)  
            # 2. Updating old data with new data
            data.update(new_dict)
            # 3.Writing into json file
            json.dump(data,file,indent=4)

But it shows json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

First you need to open the file in mode="r+" . Update the old data with new, then seek(0) to the beginning of the file, write your updated json data, and then truncate the rest:

with open("data.json", mode="r+") as file:
    file.seek(0, 2)
    if file.tell():
        file.seek(0)
        data = json.load(file)  
        data.update(new_dict)
    else:
        data = new_dict
    file.seek(0)
    json.dump(data, file, indent=4)
    file.truncate()

Reason it doesn't work with a+ mode is that it will always write at the end of the file, irrespective of seek(0) . So your updated json data just gets appended to the older one like a normal text data, but since its not a valid json syntax, it causes JSON Decode error.

Check here for more detailed info on how the different open modes work.

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