Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding and saving to list in external json file

I’m very new to Python and I’m struggling when it comes to saving the data that the user has entered to a json file when quitting the application. Also every time I run my code all the data inside the json file is wiped. When I enter the input to save and exit I get this error code:

Traceback (most recent call last):
  File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 86, in <module>
    main_menu()
  File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 23, in main_menu
    save()
  File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 82, in save
    patients_file.write(finallist)
io.UnsupportedOperation: not writable

Here is my code below:

import json
patients_file = open("patients.json", "r")
loaded_patients = json.load(patients_file)

def main_menu():
    '''Function docstring documentation here'''
    print("\nSIT Data Entry Menu")
    print("==========================")
    print("1: Print Patients' List\n2: Add Patient\n3: Delete Patient\n4: Exit")
    print("==========================")
    input1 = input("Enter your menu selection:")
    if input1 == "1":
        patients_list()
    elif input1 == "2":
        add_patient()
    elif input1 == "3":
        remove_patient()
    elif input1 == "4":
        save()
    else:
        print ("Please enter a valid input")
        main_menu()

def patients_list():
    print("\nSIT current patients:\n")
    loaded_patients.sort(key=str.casefold)
    for number, item in enumerate(loaded_patients, start=1):
        print(number, item)
    print("\nTotal number of registered patients is", len(loaded_patients))
    main_menu()

def add_patient():
    newpatient = input("\nEnter new Patient -> Lastname Firstname:")
    print ("Do the details you have entered look correct? y/n")
    confirm = input()
    if confirm == "y":
        loaded_patients.append(newpatient)
        print ("Patient successfully added to list")
        main_menu()
    elif confirm == "n":
        print ("Patient import cancelled")
        add_patient()
    else:
        print ("Please enter a valid input")
        add_patient()

def remove_patient():
    print ("Which of the following patients would you like to remove?")
    loaded_patients.sort(key=str.casefold)
    for number, item in enumerate(loaded_patients, start=1):
        print(number, item)
    try:
        removepatient = int(input("\nEnter the number of the patient you would like to remove"))
        print ("Does the patient number you have entered look correct? y/n")
        delconfirm = input()
        if delconfirm == "y":
            try:
                removepatient = (removepatient - 1)
                loaded_patients.pop(removepatient)
                print ("Patient was successfully removed from the list")
                main_menu()
            except IndexError:
                print("Please enter a valid input")
                remove_patient()
        elif delconfirm == "n":
            print ("Deletion cancelled")
            remove_patient()
        else:
            print ("Please enter a valid input")
            remove_patient()
    except ValueError:
        print ("Please enter a valid input")
        remove_patient()

def save():
    open("patients.json", "w")
    finallist = json.dumps(loaded_patients)
    patients_file.write(finallist)
    print("Patient List successfully saved")
    quit()

main_menu()

I store the json file in the same directory and all it contains is a list:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["Soreback Leigh", "Neckache Annette", "Sorefoot Jo", "Kaputknee Matt", "Brokentoe Susan", "Tornligament Alex"]

If anyone could help me out and let me know what I’m doing wrong or any simpler method I could use, it would be greatly appreciated.
Thanks

>Solution :

You are trying to write to patients_file, which you opened in read-only mode.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading