Contact Book Project (code) in Python

← Back to Projects

Contact Book in Python.

About the project: Creating a Contact Book project in Python. This will be a self-contained script that allows to store, view, and manage contact information.

This Python script is a complete and interactive Contact Book application.

It provides a menu-driven interface for managing contacts, and all your changes are saved to a file so that they will be there the next time you use the app.

Contact Book Project:

The program will use a dictionary to store contacts and will provide a menu-driven interface to perform actions like adding, viewing, and deleting contacts.

All contacts will be saved to a JSON file so that they are persistent between sessions.


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# contact_book.py

import json
import os

CONTACTS_FILE = "contacts.json"

def load_contacts():
    """
    Loads contacts from a JSON file. If the file doesn't exist, it returns an empty dictionary.
    """
    if os.path.exists(CONTACTS_FILE) and os.stat(CONTACTS_FILE).st_size > 0:
        try:
            with open(CONTACTS_FILE, 'r') as f:
                return json.load(f)
        except json.JSONDecodeError:
            print("Warning: Contacts file is corrupted or empty. Starting with a new contact book.")
            return {}
    return {}

def save_contacts(contacts):
    """
    Saves the contacts dictionary to a JSON file.
    """
    with open(CONTACTS_FILE, 'w') as f:
        json.dump(contacts, f, indent=4)
    print("Contacts saved successfully.")

def add_contact(contacts):
    """
    Adds a new contact to the dictionary.
    """
    name = input("Enter contact name: ").strip()
    if not name:
        print("Name cannot be empty. Contact not added.")
        return

    phone_number = input("Enter phone number: ").strip()
    email = input("Enter email address: ").strip()

    contacts[name] = {
        "phone_number": phone_number,
        "email": email
    }
    print(f"Contact '{name}' added.")

def view_contacts(contacts):
    """
    Displays all saved contacts.
    """
    if not contacts:
        print("\nNo contacts found.")
        return

    print("\n--- Your Contacts ---")
    for name, details in contacts.items():
        print(f"\nName: {name}")
        print(f"  Phone: {details.get('phone_number', 'N/A')}")
        print(f"  Email: {details.get('email', 'N/A')}")
    print("---------------------")

def search_contact(contacts):
    """
    Searches for a contact by name and displays their details.
    """
    name = input("Enter the name of the contact to search for: ").strip()
    if name in contacts:
        details = contacts[name]
        print(f"\n--- Contact Found ---")
        print(f"Name: {name}")
        print(f"  Phone: {details.get('phone_number', 'N/A')}")
        print(f"  Email: {details.get('email', 'N/A')}")
        print("---------------------")
    else:
        print(f"Contact '{name}' not found.")

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

def main():
    """
    Main function to run the Contact Book app with a menu.
    """
    contacts = load_contacts()

    print("--- Python Contact Book ---")

    while True:
        print("\nMenu:")
        print("1. Add a new contact")
        print("2. View all contacts")
        print("3. Search for a contact")
        print("4. Delete a contact")
        print("5. Quit and Save")

        choice = input("Enter your choice (1-5): ").strip()

        if choice == '1':
            add_contact(contacts)
        elif choice == '2':
            view_contacts(contacts)
        elif choice == '3':
            search_contact(contacts)
        elif choice == '4':
            delete_contact(contacts)
        elif choice == '5':
            save_contacts(contacts)
            print("Exiting Contact Book. Goodbye!")
            break
        else:
            print("Invalid choice. Please enter a number between 1 and 5.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()