레슨 8 / 9·25분
실전: 주소록 관리 프로그램
프로젝트 개요
지금까지 배운 내용을 활용하여 주소록 관리 프로그램을 만들어 봅시다. 연락처를 추가, 검색, 삭제하고 파일에 저장하는 CLI 프로그램입니다.
Contact 클래스 정의
python
import json
import os
class Contact:
def __init__(self, name, phone, email=""):
self.name = name
self.phone = phone
self.email = email
def to_dict(self):
return {
"name": self.name,
"phone": self.phone,
"email": self.email
}
@classmethod
def from_dict(cls, data):
return cls(data["name"], data["phone"], data.get("email", ""))
def __str__(self):
info = self.name + " | " + self.phone
if self.email:
info += " | " + self.email
return infoAddressBook 클래스
python
class AddressBook:
def __init__(self, filename="contacts.json"):
self.filename = filename
self.contacts = []
self.load()
def add(self, contact):
self.contacts.append(contact)
self.save()
print(contact.name + " 추가 완료")
def search(self, keyword):
results = [
c for c in self.contacts
if keyword.lower() in c.name.lower()
or keyword in c.phone
]
return results
def delete(self, name):
before = len(self.contacts)
self.contacts = [
c for c in self.contacts if c.name != name
]
if len(self.contacts) < before:
self.save()
print(name + " 삭제 완료")
else:
print(name + "을(를) 찾을 수 없습니다")
def list_all(self):
if not self.contacts:
print("주소록이 비어 있습니다")
return
for i, c in enumerate(self.contacts, 1):
print(str(i) + ". " + str(c))
def save(self):
data = [c.to_dict() for c in self.contacts]
with open(self.filename, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def load(self):
if os.path.exists(self.filename):
with open(self.filename, "r", encoding="utf-8") as f:
data = json.load(f)
self.contacts = [Contact.from_dict(d) for d in data]메인 루프
python
def main():
book = AddressBook()
print("=== 주소록 관리 프로그램 ===")
while True:
print("\n[1] 추가 [2] 검색 [3] 목록 [4] 삭제 [5] 종료")
choice = input("선택: ").strip()
if choice == "1":
name = input("이름: ").strip()
phone = input("전화번호: ").strip()
email = input("이메일 (선택): ").strip()
book.add(Contact(name, phone, email))
elif choice == "2":
keyword = input("검색어 (이름/전화): ").strip()
results = book.search(keyword)
if results:
for c in results:
print(" ->", c)
else:
print("검색 결과가 없습니다")
elif choice == "3":
book.list_all()
elif choice == "4":
name = input("삭제할 이름: ").strip()
book.delete(name)
elif choice == "5":
print("프로그램을 종료합니다.")
break
else:
print("잘못된 입력입니다")
if __name__ == "__main__":
main()💡
이 프로젝트는 클래스, 파일 I/O, 예외 처리, 리스트 컴프리헨션 등 지금까지 배운 핵심 개념을 모두 활용합니다. 기능을 추가해 보세요: 수정, 정렬, CSV 내보내기 등.