Skip to content
Python project #12Intermediate

Contact Book

Store contacts with validated Indian mobile numbers and emails, tags, search, editing and CSV export.

Estimated time
~3 hours to build
Files
4 files · 331 lines
Technologies
Python 3, re, csv, io.StringIO

Introduction

A contact book is a small database with real validation needs: names should be names, phone numbers should be dialable, emails should look like emails and duplicates should be caught. This project uses regular expressions for all of it.

Problem statement

Add contacts as 'name | phone | email | tags'. Normalise names to title case, accept Indian mobile numbers with or without +91, spaces or hyphens and store them in one format, lower-case emails and reject invalid ones, and refuse a phone number that already belongs to someone. Support listing (sorted by name), searching across all fields, filtering by tag, editing a field, deleting and exporting to CSV.

Objectives

  • Validate formats with regular expressions
  • Normalise data before storing it
  • Prevent duplicates
  • Write CSV with the csv module

Features

  • Phone and email validation and normalisation
  • Duplicate phone detection
  • Search by name, phone or email
  • Tags and tag filtering
  • Edit, delete and CSV export

Concepts demonstrated

  • Regular expressions
  • Data normalisation
  • Uniqueness constraints
  • CSV output

System architecture

clean_name, clean_phone and clean_email validate and normalise each field, raising ContactError. ContactBook stores Contact dataclasses, checks phone uniqueness and resolves list numbers through the sorted listing. run dispatches commands; export writes CSV through csv.writer into a StringIO.

Folder structure

TextProject tree
contact-book/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

166 lines
Pythonmain.py
"""Contact Book: add, validate, search, tag, edit, delete and export contacts.
Commands:
add <name> | <phone> | <email> | <tags, comma separated>
list
search <text> name, phone or email
tag <tag>
edit <n> name|phone|email <value>
delete <n>
export print all contacts as CSV
quit
Phone numbers are Indian mobile numbers: 10 digits starting 6-9, optionally with +91.
"""
import csv
import io
import re
import sys
from dataclasses import dataclass, field
PHONE = re.compile(r"(?:\+?91[\s-]?)?([6-9]\d{4})[\s-]?(\d{5})")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")
class ContactError(Exception):
pass
@dataclass
class Contact:
name: str
phone: str
email: str = ""
tags: list[str] = field(default_factory=list)
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def clean_name(text: str) -> str:
name = " ".join(text.split())
if not name or not re.fullmatch(r"[A-Za-z .'-]+", name):
raise ContactError(f"'{text}' is not a valid name")
return name.title()
def clean_phone(text: str) -> str:
match = PHONE.fullmatch(text.strip())
if not match:
raise ContactError(f"'{text}' is not a valid Indian mobile number")
return "+91 " + match.group(1) + " " + match.group(2)
def clean_email(text: str) -> str:
text = text.strip().lower()
if text and not EMAIL.fullmatch(text):
raise ContactError(f"'{text}' is not a valid email address")
return text
class ContactBook:
def __init__(self):
self.contacts: list[Contact] = []
def sorted(self) -> list[Contact]:
return sorted(self.contacts, key=lambda c: c.name.lower())
def check_unique(self, phone: str, ignore: Contact | None = None) -> None:
for c in self.contacts:
if c is not ignore and c.phone == phone:
raise ContactError(f"{phone} already belongs to {c.name}")
def add(self, text: str) -> Contact:
parts = [p.strip() for p in text.split("|")]
if len(parts) < 2:
raise ContactError("format: add <name> | <phone> | <email> | <tags>")
parts += [""] * (4 - len(parts))
contact = Contact(clean_name(parts[0]), clean_phone(parts[1]), clean_email(parts[2]),
sorted({t.strip().lower() for t in parts[3].split(",") if t.strip()}))
self.check_unique(contact.phone)
self.contacts.append(contact)
return contact
def by_number(self, text: str) -> Contact:
listing = self.sorted()
if not text.isdigit() or not 1 <= int(text) <= len(listing):
raise ContactError(f"no contact number {text} (see 'list')")
return listing[int(text) - 1]
def show(contacts: list[Contact], numbered: bool = True) -> None:
if not contacts:
print(" (no contacts)")
for i, c in enumerate(contacts, 1):
prefix = f"{i:>2}. " if numbered else " - "
tags = f" [{', '.join(c.tags)}]" if c.tags else ""
print(f" {prefix}{c.name:<16}{c.phone:<17}{c.email or '-':<24}{tags}".rstrip())
def run(book: ContactBook, line: str) -> None:
command, _, rest = line.partition(" ")
command = command.lower()
if command == "add":
c = book.add(rest)
print(f"Saved {c.name} ({c.phone})")
elif command == "list":
show(book.sorted())
elif command == "search":
text = rest.lower().replace(" ", "")
show([c for c in book.sorted() if text in (c.name + c.phone + c.email).lower().replace(" ", "")], numbered=False)
elif command == "tag":
show([c for c in book.sorted() if rest.lower() in c.tags], numbered=False)
elif command == "edit":
number, field_name, value = (rest.split(maxsplit=2) + ["", "", ""])[:3]
contact = book.by_number(number)
if field_name == "name":
contact.name = clean_name(value)
elif field_name == "phone":
phone = clean_phone(value)
book.check_unique(phone, ignore=contact)
contact.phone = phone
elif field_name == "email":
contact.email = clean_email(value)
else:
raise ContactError("you can edit name, phone or email")
print(f"Updated {contact.name}: {field_name} = {getattr(contact, field_name)}")
elif command == "delete":
contact = book.by_number(rest)
book.contacts.remove(contact)
print(f"Deleted {contact.name}")
elif command == "export":
buffer = io.StringIO()
writer = csv.writer(buffer, lineterminator="\n")
writer.writerow(["name", "phone", "email", "tags"])
for c in book.sorted():
writer.writerow([c.name, c.phone, c.email, ";".join(c.tags)])
print(buffer.getvalue(), end="")
else:
raise ContactError("unknown command (add, list, search, tag, edit, delete, export, quit)")
def main() -> None:
book = ContactBook()
print("Contact Book")
while True:
line = ask("> ")
if line is None or line.lower() == "quit":
break
if line:
try:
run(book, line)
except ContactError as error:
print(f"Error: {error}")
print(f"{len(book.contacts)} contact(s) saved.")
if __name__ == "__main__":
main()

What each file does

main.py
Validation helpers, the Contact and ContactBook classes, the command handlers and the loop.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Contact Book
> add asha rao | 98450 12345 | Asha.Rao@Example.com | friends, college
Saved Asha Rao (+91 98450 12345)
> add Ravi Kumar | +91-9123456789 | ravi@mail.co.in | work
Saved Ravi Kumar (+91 91234 56789)
> add Meera | 7012345678 | | family
Saved Meera (+91 70123 45678)
> add Kiran | 12345 | kiran@example.com
Error: '12345' is not a valid Indian mobile number
> add Sana | 9988776655 | sana@ | friends
Error: 'sana@' is not a valid email address
> add R2D2 | 9876501234
Error: 'R2D2' is not a valid name
> add Duplicate | 9845012345
Error: +91 98450 12345 already belongs to Asha Rao
> list
1. Asha Rao +91 98450 12345 asha.rao@example.com [college, friends]
2. Meera +91 70123 45678 - [family]
3. Ravi Kumar +91 91234 56789 ravi@mail.co.in [work]
> search 98450
- Asha Rao +91 98450 12345 asha.rao@example.com [college, friends]
> search mail
- Ravi Kumar +91 91234 56789 ravi@mail.co.in [work]
> tag friends
- Asha Rao +91 98450 12345 asha.rao@example.com [college, friends]
> edit 2 email meera@family.org
Updated Meera: email = meera@family.org
> edit 3 phone 7012345678
Error: +91 70123 45678 already belongs to Meera
> edit 3 phone 9000012345
Updated Ravi Kumar: phone = +91 90000 12345
> edit 9 name Nobody
Error: no contact number 9 (see 'list')
> delete 1
Deleted Asha Rao
> export
name,phone,email,tags
Meera,+91 70123 45678,meera@family.org,family
Ravi Kumar,+91 90000 12345,ravi@mail.co.in,work
> quit
2 contact(s) saved.
Input
add asha rao | 98450 12345 | Asha.Rao@Example.com | friends, college
add Ravi Kumar | +91-9123456789 | ravi@mail.co.in | work
add Meera | 7012345678 | | family
add Kiran | 12345 | kiran@example.com
add Sana | 9988776655 | sana@ | friends
add R2D2 | 9876501234
add Duplicate | 9845012345
list
search 98450
search mail
tag friends
edit 2 email meera@family.org
edit 3 phone 7012345678
edit 3 phone 9000012345
edit 9 name Nobody
delete 1
export
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • '98450 12345' and '+91-9123456789' are stored as '+91 98450 12345' and '+91 91234 56789'.
  • A 5-digit phone, 'sana@', the name R2D2 and a duplicate phone are rejected.
  • Editing contact 3's phone to Meera's number is refused; the final export lists two contacts.

Common errors

The same number is stored in different formats

Normalise every phone number to one format before comparing or saving.

Commas in tags break the CSV

Let csv.writer quote fields, or join tags with ';' as export does.

Possible improvements

  • Save contacts to a JSON or vCard file
  • Add birthdays and an upcoming-birthdays report
  • Import contacts from CSV

Additional challenges

  1. 1Detect likely duplicates with similar names (e.g. 'Ravi K' and 'Ravi Kumar').
  2. 2Support landline numbers with STD codes.
  3. 3Add undo for the last delete.

Built and tested it yourself? Mark it to update your dashboard.