I'm basically creating a contact book, and I want to do it storing data on JSON to practice it. I have sort a code that allows it from a dictionary, but the problem is that when I rerun the script, another dictionary is appended into the existing one, creating a couple of extra braces which throws the error "End of file expected."
This is the code:
import json
new_contacts = {}
def contacts():
while True:
name = input("Contact's name: ")
email = input("Email: ")
number = input("Phone number: ")
new_contacts[name] = {"email": email, "number": number}
"""cursor.execute(
'INSERT INTO contacts VALUES (?, ?, ?)',
(name, email, number)
)"""
restart_or_not = input("Continue? y/n ").lower()
if restart_or_not == "y":
print(new_contacts)
continue
else:
with open('contact_book.json', 'a') as file:
json.dump(new_contacts, file, indent=4)
break
contacts()
And this is a sample of a JSON that comes out from it:
{
"d": {
"email": "e",
"number": "3"
},
"h": {
"email": "y",
"number": "6"
},
"f": {
"email": "r",
"number": "3"
},
"n": {
"email": "j",
"number": "9"
}
}{
"g": {
"email": "j",
"number": "0"
}
}
The first four entries don't create any problem because they are appended in the same run, but if I quit the program and rerun it (example "g") then the new dictionary creates the conflict. Any tips?