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...