Contact Book Application in Python



The contact book Python application is a simple yet effective tool for managing personal contacts. With this application, users can add, view, delete, and search for contacts, while ensuring that phone numbers are properly validated. The contact book stores all the information in a JSON file, making it easy to persist data across sessions.

Working Process of Contact Book Application

The contact book application is designed to manage your contacts using Python. Here is how it works −

  • Loading Contacts When the app starts, it checks for an existing contact.json file. If found, it loads your saved contacts into the program.
  • Adding Contacts You can add a new contact by providing a name, phone number, and email. The phone number is checked to ensure it’s numeric and doesn’t exceed 10 digits.
  • Viewing Contacts To see all your contacts, you simply choose the view option. The app displays each contact’s details in a user-friendly format.
  • Deleting Contacts If you need to remove a contact, you just input the contact's name, and if it exists, the app deletes it from the list.
  • Searching Contacts You can quickly find a contact by name. The app will show the details if the contact is in the list.
  • Saving Contacts When you exit the app, your changes are saved to contacts.json, so you don’t lose any information.

Python Code to Implement Contact Book Application

import json
import os
import re

# File to store contacts
CONTACTS_FILE = 'contacts.json'

def load_contacts():
   """Load contacts from the JSON file."""
   if os.path.exists(CONTACTS_FILE):
      with open(CONTACTS_FILE, 'r') as file:
         return json.load(file)
   return {}

def save_contacts(contacts):
   """Save contacts to the JSON file."""
   with open(CONTACTS_FILE, 'w') as file:
      json.dump(contacts, file, indent=4)

def add_contact(contacts):
   """Add a new contact with phone number validation."""
   name = input("Enter contact name: ").strip()
   phone = input("Enter contact phone number: ").strip()

   # Validate phone number length
   if len(phone) > 10:
      print("Phone number should not exceed 10 digits.")
      return

   # Optional: Further validate phone number format (e.g., only digits)
   if not re.match(r'^\d+$', phone):
      print("Phone number should contain only digits.")
      return

   email = input("Enter contact email: ").strip()
   contacts[name] = {'phone': phone, 'email': email}
   print(f"Contact '{name}' added.")

def view_contacts(contacts):
   """View all contacts."""
   if not contacts:
      print("No contacts found.")
      return
   for name, info in contacts.items():
      print(f"Name: {name}")
      print(f"Phone: {info['phone']}")
      print(f"Email: {info['email']}\n")

def delete_contact(contacts):
   """Delete a contact."""
   name = input("Enter contact name to delete: ").strip()
   if name in contacts:
      del contacts[name]
      print(f"Contact '{name}' deleted.")
   else:
      print("Contact not found.")

def search_contact(contacts):
   """Search for a contact."""
   name = input("Enter contact name to search: ").strip()
   if name in contacts:
      info = contacts[name]
      print(f"Name: {name}")
      print(f"Phone: {info['phone']}")
      print(f"Email: {info['email']}")
   else:
      print("Contact not found.")

def main():
   contacts = load_contacts()
   while True:
      print("\nContact Book")
      print("1. Add Contact")
      print("2. View Contacts")
      print("3. Delete Contact")
      print("4. Search Contact")
      print("5. Exit")
      choice = input("Enter your choice: ").strip()
        
      if choice == '1':
         add_contact(contacts)
      elif choice == '2':
         view_contacts(contacts)
      elif choice == '3':
         delete_contact(contacts)
      elif choice == '4':
         search_contact(contacts)
      elif choice == '5':
         save_contacts(contacts)
         print("Contacts saved. Exiting...")
         break
      else:
         print("Invalid choice. Please try again.")

if __name__ == "__main__":
   main()

Output

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 1
Enter contact name: Sudhir
Enter contact phone number: 1234567890
Enter contact email: [email protected]
Contact 'Sudhir' added.

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 2 1
Enter contact name: Krishna
Enter contact phone number: 1118882340
Enter contact email: kkk@gmail, .com
Contact 'Krishna' added.

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 2
Name: Sudhir
Phone: 1234567890
Email: [email protected]

Name: Krishna
Phone: 1118882340
Email: [email protected]


Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 5
Contacts saved. Exiting...

This is normal output, but if you write more than 10 numbers in phone number it will show −

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 1
Enter contact name: Sudhir
Enter contact phone number: 777   123456789012
Phone number should not exceed 10 digits.

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 5
Contacts saved. Exiting...
python_projects_from_basic_to_advanced.htm
Advertisements