Oqhax
Oqhax

Reputation: 417

Appending data to JSON file with python?

I have made a small python program which writes some string inputs into a JSON file:

import json

while True:
    name = input('What is your name?')
    surname = input('What is your surname')
    age = input('How old are you?')

    with open("info_.json", "w") as data:
        information = {name: {'surname': surname, 'age': age}}
        data.write(json.dumps(information))
        data.close()

    with open("info_.json", "r") as info_read:
        dict_info = json.loads(info_read.read())
        name_d = dict_info.get(name)
        print(name_d)

It works perfectly fine, althought the second time of the loop, the inputs overwrite the information that was written the first time. Is there any way of adding more data to a file, without overwriting? Thank you

Upvotes: 3

Views: 17082

Answers (2)

Gaurav Gandhi
Gaurav Gandhi

Reputation: 3201

One does not simply, append into JSON file

You first need to load all JSON data, append to it and write it back.

import json

json_path = "info_.json"

def write_json(data, filename): 
    """Write json file with provided data"""
    with open(filename,'w') as f: 
        json.dump(data, f, indent=4) 


def print_user_info(name):
    """Read json data file, print specified user"""
    with open(json_path, "r") as info_read:
        info_data = json.loads(info_read.read())
        info_data = dict(info_data)
        user_data = info_data.get(name)
        print(f"{name} : {user_data}")


def update_user_info(name, surname, age):
    """Fetch existing json data, append to it, write to file and print new user details from file"""
    with open(json_path, "r") as info_fp:
        # Read existing data and append to new data it
        info_data = json.load(info_fp)
        info_data[name] = {'surname': surname, 'age': age}

        # Write updated data
        write_json(info_data, filename=json_path)

        # Print new user details from json file
        print_user_info(name)


# Function to take user inputs   
def new_user_input():
    """Take user inputs for new user data, update that into json data file"""
    name = input('What is your name? ')
    surname = input('What is your surname? ')
    age = input('How old are you? ')

    update_user_info(name, surname, age)


if __name__ == '__main__':
    new_user_input()

Upvotes: 1

Chetan_Vasudevan
Chetan_Vasudevan

Reputation: 2414

So file mode = 'r' is to read the file and file mode = 'w' is to write to file, in the for loop when you start looping it multiple times it should get appended which is file mode = 'a'.If you use 'w' it tries to overwrite the existing text in file.

    with open("info_.json", "a") as data:
        information = {name: {'surname': surname, 'age': age}}
        data.write(json.dumps(information))
        data.close()

So, when you make the file mode = 'w' and then execute the for loop for the first time the data gets into file perfectly and when the for loop gets executed second time the data gets overwritten on the previously existing data in file.So file mode='a' is a process where the data gets added/appended into the file for n number of times the for loop runs

Upvotes: 8

Related Questions