-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontact_CLI.py
More file actions
65 lines (55 loc) · 2.03 KB
/
contact_CLI.py
File metadata and controls
65 lines (55 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
# 1. Setup: Load existing data or start fresh
FILE_NAME = "contacts.txt"
contacts = []
# Load data from file if it exists
if os.path.exists(FILE_NAME):
with open(FILE_NAME, "r") as file:
for line in file:
# Each line is "Name:Phone", so we split it
name, phone = line.strip().split(":")
contacts.append({"name": name, "phone": phone})
while True:
print("\n--- Contact Book Menu ---")
print("1. Add Contact")
print("2. Search Contact")
print("3. Delete Contact")
print("4. Save & Exit")
choice = input("Choose an option (1-4): ")
if choice == "1":
# ADD CONTACT
name = input("Enter Name: ")
phone = input("Enter Phone: ")
# Create a dictionary and add to our list
contacts.append({"name": name, "phone": phone})
print(f"Contact for {name} added!")
elif choice == "2":
# SEARCH CONTACT
search_name = input("Who are you looking for? ")
found = False
for person in contacts:
if person["name"].lower() == search_name.lower():
print(f"Found: {person['name']} - {person['phone']}")
found = True
break
if not found:
print("Contact not found.")
elif choice == "3":
# DELETE CONTACT
del_name = input("Enter name to delete: ")
# We create a new list excluding the person we want to delete
original_count = len(contacts)
contacts = [p for p in contacts if p["name"].lower() != del_name.lower()]
if len(contacts) < original_count:
print(f"Deleted {del_name}.")
else:
print("No contact found with that name.")
elif choice == "4":
# SAVE AND EXIT (File I/O)
with open(FILE_NAME, "w") as file:
for person in contacts:
file.write(f"{person['name']}:{person['phone']}\n")
print("Contacts saved to contacts.txt. Goodbye!")
break
else:
print("Invalid choice, try again.")