Thursday, February 12, 2026

Python Contact Management with JSON

 
 import json  
 import os  
 
 CONTACTS_FILE = "contacts.json"  
 
 def load_contacts():  
   if not os.path.exists(CONTACTS_FILE):  
     return[]  
   try:  
     with open(CONTACTS_FILE, 'r') as file:  
       return json.load(file)  
   except (json.JSONDecodeError, IOError):  
     print("Error reading contacts file. Starting with an empty list")  
     return [] 
     
 def save_contacts(contacts):  
   try:   
     with open(CONTACTS_FILE, 'w') as file:  
       json.dump(contacts, file, indent=4)  
     print("Contact saved successfully")  
   except IOError as e:  
     print(f"Error saving contacts: {e}")  
     
 def create_contact(contacts):  
   print("\n--- Add New Contact ---")  
   name = input("Enter name : ").strip()  
   if not name:  
     print("Name cannot be empty.")  
     return  
   location = input("Enter location : ").strip()  
   if not location:  
     print("Location cannot be empty.")  
     return  
   new_contact= {  
     'name': name,  
     'location': location  
   }  
   contacts.append(new_contact)  
   save_contacts(contacts)  
   print(f"Contact '{name}' added successfully")  
   
 def read_contacts(contacts):  
   print("\n-- All Contacts --")  
   if not contacts:  
     print("No contacts found")  
     return  
   for index, contact in enumerate(contacts, start=1):  
     print(f"{index}. Name: {contact['name']}, Location: {contact['location']}")  
     
 def main():  
   contacts = load_contacts()  
   # read_contacts()  
   while True:  
     print("\n== Contact Management System ==")  
     print("1. Add Contact")  
     print("2 View Contacts")  
     print("3. Exit")  
     choice = input("Enter your choice (1-3): ").strip()  
     print(choice)  
     if choice == '1':  
       create_contact(contacts)  
     elif choice == '2':  
       read_contacts(contacts)  
     elif choice == '3':  
       print("Exiting Contact Management System. Goodbye")  
       break  
     else:  
       print("Invalid choice. Please enter a number between 1 and 3")  
       
 if __name__=="__main__":  
   main()  

No comments:

Post a Comment