Database of Contacts using File Storage - Python Programming Exercise

In this exercise, you will develop a Python program that extends the "contacts database" by implementing functionality to load data from a file at the start of each session (if the file is present). This exercise is perfect for practicing file handling, data serialization, and user interaction in Python. By implementing this program, you will gain hands-on experience in handling file operations, data serialization, and user interaction in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

Database Of Contacts Using File Storage

 Objective

Develop a Python program that extends the "contacts database" by implementing functionality to load data from a file at the start of each session (if the file is present). Additionally, it should save the data to the file when the session finishes, ensuring that any changes made during the session are available for the following one.

 Example Python Exercise

 Copy Python Code
import os
import pickle

# Class to represent a Contact with name, phone, and email
class Contact:
    def __init__(self, name, phone, email):
        self.name = name  # Contact's name
        self.phone = phone  # Contact's phone number
        self.email = email  # Contact's email address

    # String representation of a contact
    def __str__(self):
        return f"Name: {self.name}, Phone: {self.phone}, Email: {self.email}"

# Class to manage the database of contacts
class ContactsDatabase:
    def __init__(self, file_name):
        self.file_name = file_name  # File name to load/save contacts
        self.contacts = []  # List to store contacts
        self.load_from_file()  # Load existing contacts from file (if any)

    # Method to add a new contact
    def add_contact(self, name, phone, email):
        new_contact = Contact(name, phone, email)  # Create a new Contact object
        self.contacts.append(new_contact)  # Add the contact to the list
        print(f"Contact {name} added.")  # Notify that the contact has been added

    # Method to list all contacts in the database
    def list_contacts(self):
        if not self.contacts:  # Check if there are no contacts
            print("No contacts available.")  # Inform the user that there are no contacts
        else:
            for contact in self.contacts:  # Loop through the list of contacts
                print(contact)  # Print each contact's details

    # Method to save the contacts list to a file
    def save_to_file(self):
        try:
            with open(self.file_name, 'wb') as file:  # Open the file in write-binary mode
                pickle.dump(self.contacts, file)  # Serialize and save the contacts list to the file
            print("Contacts saved successfully.")  # Notify that contacts have been saved
        except Exception as e:  # In case of an error while saving the file
            print(f"Error saving contacts: {e}")  # Print the error message

    # Method to load contacts from a file
    def load_from_file(self):
        if os.path.exists(self.file_name):  # Check if the file exists
            try:
                with open(self.file_name, 'rb') as file:  # Open the file in read-binary mode
                    self.contacts = pickle.load(file)  # Deserialize and load the contacts list from the file
                print("Contacts loaded successfully.")  # Notify that contacts have been loaded
            except Exception as e:  # In case of an error while reading the file
                print(f"Error loading contacts: {e}")  # Print the error message
        else:
            print("No previous contacts found. Starting fresh.")  # Inform that no previous data exists

# Main function to drive the program
def main():
    file_name = "contacts.pkl"  # Define the file name to store contacts
    db = ContactsDatabase(file_name)  # Create an instance of the ContactsDatabase class

    while True:  # Infinite loop to show the menu until the user exits
        print("\n--- Contacts Database ---")  # Displaying the menu options
        print("1. Add Contact")  # Option to add a new contact
        print("2. List Contacts")  # Option to list all contacts
        print("3. Exit")  # Option to exit the program

        choice = input("Choose an option: ")  # Get the user's choice

        if choice == '1':  # If the user chooses to add a contact
            name = input("Enter name: ")  # Prompt for the contact's name
            phone = input("Enter phone number: ")  # Prompt for the contact's phone number
            email = input("Enter email address: ")  # Prompt for the contact's email address
            db.add_contact(name, phone, email)  # Add the contact to the database
        elif choice == '2':  # If the user chooses to list contacts
            db.list_contacts()  # Display all the contacts
        elif choice == '3':  # If the user chooses to exit
            db.save_to_file()  # Save the current contacts to the file
            print("Exiting the program...")  # Notify that the program is exiting
            break  # Exit the loop and end the program
        else:
            print("Invalid choice. Please try again.")  # If the input is invalid, ask the user to try again

# Run the main function when the script is executed
if __name__ == "__main__":
    main()

 Output

--- Contacts Database ---
1. Add Contact
2. List Contacts
3. Exit
Choose an option: 1
Enter name: John Doe
Enter phone number: 123-456-7890
Enter email address: john.doe@example.com
Contact John Doe added.

--- Contacts Database ---
1. Add Contact
2. List Contacts
3. Exit
Choose an option: 2
Name: John Doe, Phone: 123-456-7890, Email: john.doe@example.com

--- Contacts Database ---
1. Add Contact
2. List Contacts
3. Exit
Choose an option: 3
Contacts saved successfully.
Exiting the program...

 Share this Python Exercise

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Transform a Text File to Uppercase

    In this exercise, you will develop a Python program that reads the contents of a text file and writes it to a new file, converting all lowercase letters to uppercase....

  •  Transform any file content to uppercase

    In this exercise, you will develop a Python program that reads any file and transfers its content to another file, converting all lowercase letters to uppercase. This...

  •  Reversing File Content

    In this exercise, you will develop a Python program to "invert" a file. This exercise is perfect for practicing file handling, byte manipulation, and loops in ...

  •  File Encryption Tool

    In this exercise, you will develop a Python program to encode the content of a text file into a new file, transforming the text in a way that it is not easily readabl...

  •  Word Counter

    In this exercise, you will develop a Python program to count the total number of words in a given text file. This exercise is perfect for practicing file handl...

  •  BMP Dimensions with BinaryReader

    In this exercise, you will develop a Python program to read the dimensions (width and height) of a BMP file using a BinaryReader-like approach. This exercise i...