Click here to Skip to main content
15,946,988 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why update is not working, it take all the inputs correctly but print the else statement. How to handle the exception value error when user put string instead of int.

What I have tried:

Python
# import json
import json
from textwrap import indent
# filename
filename = "emp.json"

emp_dic =[{
      "name" : input("Enter employee name : "),
      "employee_id":"A2022-100",
      "city" : input ("Enter city : "),
      "experience" :int(input("Enter experience :")),
      "ctc" : int(input("Enter CTC : ")),
      "age" : int(input("Enter age : ")),
      "contact" : int(input("Enter contact : ")) 
      }]
#try:
#   print("experience")
#except: ValueError
#print("Invalid input")
dic = json.dumps(emp_dic , indent=4)
with open (filename,"w") as file:
     file.write(dic)
     print(dic)

# Choices function for user to select add,update,delete
def Choices():
    print("manage employee system")
    print("a - add the new employee detail")
    print("u - update the employee detail")
    print("d - delete the employee detail")
    

while True:

    # open the json file and store the datas in data variable
    with open(filename, "r") as file:
        data = json.load(file)

    # to get the last employee id in a list
    listemp = [int(data[-1]['employee_id'][6:])]

    Choices()
    # user need to select the option
    Choice = input("\nSelect a option: ")
    # add a new data to json file
    if Choice == "a":

        # to create a new employee id for new user
        emp_id = listemp[-1] + 1
        listemp.append("A2022" + ":" +str(emp_id))

        # getting all the input data from the user for new employee to add in json file
        emp_dic = {"name": input("enter your name : "),
                     "employee_id": listemp[-1],
                     "city": input("enter the city : "),
                     "experience": int(input("enter the experience : ")),
                     "ctc": int(input("enter your ctc : ")),
                     "age": int(input("enter the age : ")),
                     "contact_no": int(input("enter the contact number : "))
                     }

        # open the file and read the data and store in data variable
        with open(filename, "r") as file:
            data = json.load(file)

        # append the new employee data to data variable
        data.append(emp_dic)

        # data variable had some datas , write the data to json file
        with open(filename, "w") as file:
            json.dump(data, file,indent=4)

        print("new employee details added")

    # update the data on existing employee
    elif Choice == "u":

        # open the file and read the data and store it in data variable
        with open(filename, "r+") as file:
            data = json.load(file)
            print(data)

            #  asking the user which employee id that user must update
            Enter_id = input("Enter the employee id to update: ")

            # getting the data from file separately using index
            for index, emp in enumerate(data):

                # checking user given employee id is in the dataset already
                if Enter_id == emp['employee_id']:
                   change= input("enter what you want to change : ")
                   
                   if change == "name":
                     data[index]["name"] = input("enter your name : ")
                   elif change=="city": 
                    data[index]["city"] = input("Enter city : ")
                   elif change=="experience":
                    data[index]["experience"] = int(input("Enter experience :"))
                   elif change=="ctc":
                    data[index]["ctc"] = int(input("Enter CTC : "))
                   elif change=="age":
                    data[index]["age"] = int(input("Enter age : "))
                   elif change=="contact_no":
                    data[index]["contact_no"] = int(input("Enter contact : "))
                    #data.append([index])
                    # open the file and write the updated data to file
                    with open(filename, 'w') as data_file:
                        data = json.dump(data, data_file,indent=4)
                        print("employee detail updated")
                    #break
            # if the user gives not matching employee id
            else:
                 print("Invalid input")
    # delete the employee data in json file
    elif Choice == "d":

        # open the file and read the data and store it in data variable
        with open(filename, "r+") as file:
            data = json.load(file)
            print(data)

        # asking the employee id which user need to delete
        Enter_id = input("Enter employee_id you want to delete: ")

        # getting the data from file separately using index
        for index, emp in enumerate(data):

            # checking emp id is in the dataset
            if Enter_id == emp["employee_id"]:
                confirm = input("Do you want to delete,press y : ")

                if confirm == "y":
                    del data[index]

                    # open the file and write the data to json file
                    with open(filename, 'w') as data_file:
                        data = json.dump(data, data_file,indent=4)
                    break
        else:
            print("emp_id is not found.")

    else :
        print("Invalid Input")
Posted
Updated 14-Jun-22 0:01am
v2
Comments
Richard MacCutchan 14-Jun-22 4:45am    
What is the problem and where does it occur?

I also notice in your update function that you have opened your filename for "r+" to read some data, and you then try to open it for "w", while it is still open in read mode. This will likely lead to corrupt data. You should use different files for input and output.
Member 15667238 14-Jun-22 5:16am    
I'll update. The problem is when I enter some input for change suppose I change the city name then instead of storing the new city in the emp detail , it shows the else statement that invalid input.
Richard MacCutchan 14-Jun-22 5:46am    
We cannot guess what data you are entering, or what is in the JSON that you read in from the file. You n eed to do some more investigations to see exactly what is happening.
Member 15667238 14-Jun-22 21:10pm    
Thank you, your given solution works.

1 solution

The section in your update code looks incorrect, you have:
Python
       elif change=="contact_no":
        data[index]["contact_no"] = int(input("Enter contact : "))
        #data.append([index])
        # open the file and write the updated data to file
        with open(filename, 'w') as data_file:
            data = json.dump(data, data_file,indent=4)
            print("employee detail updated")
        #break
# if the user gives not matching employee id
else:
     print("Invalid input")

So whatever the user enters it will write back to the file. The loop will then continue until it reaches the end of the JSON entries, and print the "Invalid input" message. You need to add the break command after writing the file, but you also need an else statement for the invalid input. Something like:
Python
       elif change=="contact_no":
         data[index]["contact_no"] = int(input("Enter contact : "))
         #data.append([index])
       else:
         print("Invalid change selection")
         break # do not write to the file
       # open the file and write the updated data to file
       with open(filename, 'w') as data_file:
         data = json.dump(data, data_file,indent=4)
         print("employee detail updated")
         break # nothing more to do
# if the user gives not matching employee id
else:
     print("Invalid employee id")

Using meaningful error messages makes it clearer what the problem is.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900