학습 목표

  • 기존 텍스트 기반 프로그램에 고급 기능을 확장하는 방법을 익힌다.
  • 문자열 처리, 리스트 조작, 조건문, 반복문, 파일 입출력을 복합적으로 활용한다.

검색 및 삭제 기능 추가

12.1 메뉴 구성 확장

[1] 학생 정보 추가
[2] 전체 학생 정보 출력
[3] 이름으로 검색
[4] 이름으로 삭제
[5] 프로그램 종료

12.2 이름으로 검색 기능 구현

elif choice == "3":
    keyword = input("검색할 이름을 입력하세요: ")
    found = False

    with open("students.txt", "r") as f:
        for line in f:
            if keyword in line:
                print("찾음 →", line.strip())
                found = True

    if not found:
        print("검색 결과가 없습니다.")
  • in 키워드를 이용해 이름 포함 여부 확인

12.3 이름으로 삭제 기능 구현

elif choice == "4":
    delete_name = input("삭제할 이름을 입력하세요: ")
    lines = []

    with open("students.txt", "r") as f:
        lines = f.readlines()

    with open("students.txt", "w") as f:
        deleted = False
        for line in lines:
            if delete_name not in line:
                f.write(line)
            else:
                deleted = True

    if deleted:
        print(f"{delete_name}님의 정보가 삭제되었습니다.")
    else:
        print("해당 이름을 찾을 수 없습니다.")
  • 리스트로 전체 내용을 저장 후 필터링하여 다시 파일에 씀

정렬 기능 추가 및 실습 통합

12.4 이름 기준 정렬 출력 기능 구현

elif choice == "5":
    try:
        with open("students.txt", "r") as f:
            students = f.readlines()
            students.sort()  # 문자열 기준 오름차순 정렬
            print("\n[이름 순 정렬 출력]")
            for student in students:
                print(student.strip())
    except FileNotFoundError:
        print("학생 정보 파일이 없습니다.")
  • sort()는 리스트 안의 문자열을 알파벳 순으로 정렬

12.5 전체 통합 코드 예시

# 학생 정보 관리 프로그램 (심화 기능 포함)

while True:
    print("\n===== 학생 정보 관리 프로그램 =====")
    print("[1] 학생 정보 추가")
    print("[2] 전체 학생 정보 출력")
    print("[3] 이름으로 검색")
    print("[4] 이름으로 삭제")
    print("[5] 이름 기준 정렬 출력")
    print("[6] 프로그램 종료")

    choice = input("메뉴를 선택하세요 (1~6): ")

    if choice == "1":
        # 학생 정보 추가
        name = input("이름을 입력하세요: ")
        age = input("나이: ")
        subject = input("좋아하는 과목: ")
        score = input("점수: ")

        with open("students.txt", "a", encoding="utf-8") as f:
            f.write(f"이름: {name}, 나이: {age}, 과목: {subject}, 점수: {score}\n")

        print(f"{name}님의 정보가 저장되었습니다.")

    elif choice == "2":
        # 전체 출력
        try:
            with open("students.txt", "r", encoding="utf-8") as f:
                data = f.read()
                if data.strip() == "":
                    print("저장된 정보가 없습니다.")
                else:
                    print("\n[전체 학생 정보]")
                    print(data)
        except FileNotFoundError:
            print("파일이 존재하지 않습니다.")

    elif choice == "3":
        # 이름으로 검색
        keyword = input("검색할 이름을 입력하세요: ")
        found = False

        try:
            with open("students.txt", "r", encoding="utf-8") as f:
                for line in f:
                    if keyword in line:
                        print("찾음 →", line.strip())
                        found = True
        except FileNotFoundError:
            print("파일이 존재하지 않습니다.")

        if not found:
            print("검색 결과가 없습니다.")

    elif choice == "4":
        # 이름으로 삭제
        delete_name = input("삭제할 이름을 입력하세요: ")

        try:
            with open("students.txt", "r", encoding="utf-8") as f:
                lines = f.readlines()

            with open("students.txt", "w", encoding="utf-8") as f:
                deleted = False
                for line in lines:
                    if delete_name not in line:
                        f.write(line)
                    else:
                        deleted = True

            if deleted:
                print(f"{delete_name}님의 정보가 삭제되었습니다.")
            else:
                print("해당 이름을 찾을 수 없습니다.")
        except FileNotFoundError:
            print("파일이 존재하지 않습니다.")

    elif choice == "5":
        # 이름 기준 정렬 출력
        try:
            with open("students.txt", "r", encoding="utf-8") as f:
                students = f.readlines()
                students.sort()
                print("\n[이름 순 정렬 출력]")
                for student in students:
                    print(student.strip())
        except FileNotFoundError:
            print("학생 정보 파일이 없습니다.")

    elif choice == "6":
        print("프로그램을 종료합니다.")
        break

    else:
        print("잘못된 입력입니다. 1~6 중에서 선택해주세요.")


마무리 퀴즈

  1. 특정 키워드가 문자열에 포함되었는지 확인하는 방법은? → “** 키워드 사용**
  2. 파일 내용을 모두 가져와 처리한 뒤 다시 저장하는 작업은 어떤 상황에 필요할까요? → 삭제, 정렬 등 전체 조작이 필요한 경우
  3. 리스트의 정렬 기능을 사용하려면 어떤 함수? → “** 함수**


TechTinkerer's에서 더 알아보기

구독을 신청하면 최신 게시물을 이메일로 받아볼 수 있습니다.

댓글 남기기

  • Building a Command-Line Calculator with C++

    [Tutorial] · 2026-04-30 04:08 UTC Building a Command-Line Calculator with C++ 💡 TL;DR Learn how to build a command-line calculator in C++ that takes user input and performs basic arithmetic operations. 📚 Learning Objectives This tutorial guides you through creating a basic command-line calculator in C++. You’ll learn how to take user input, perform arithmetic…

  • Mastering Python Data Structures for Efficient Coding

    [Tutorial] · 2026-04-30 03:05 UTC Mastering Python Data Structures for Efficient Coding 💡 TL;DR Learn about Python’s fundamental data structures – arrays, lists, tuples, and dictionaries – to write efficient and scalable code. 📚 Learning Objectives This tutorial covers the essential Python data structures – arrays, lists, tuples, and dictionaries. You’ll learn about their usage,…

  • Introduction to Object-Oriented Programming in Python

    [Tutorial] · 2026-04-30 02:02 UTC Introduction to Object-Oriented Programming in Python 💡 TL;DR Learn the fundamentals of object-oriented programming in Python, including classes and objects, inheritance, and polymorphism. 📚 Learning Objectives This tutorial introduces the basics of object-oriented programming in Python, covering classes, objects, inheritance, and polymorphism. By the end of this tutorial, beginners will…

  • Complete Guide to Python List Comprehensions

    [Tutorial] · 2026-04-30 01:00 UTC Complete Guide to Python List Comprehensions 💡 TL;DR Master Python list comprehensions to write concise and efficient code for data manipulation and transformation tasks. 📚 Learning Objectives This tutorial covers the basics of Python list comprehensions, including syntax, use cases, and execution results. You’ll learn how to write efficient and…

  • Mastering Python Data Science Essentials with Pandas, NumPy, and Matplotlib

    [Tutorial] · 2026-04-29 23:56 UTC Mastering Python Data Science Essentials with Pandas, NumPy, and Matplotlib 💡 TL;DR Get started with Python data science using Pandas, NumPy, and Matplotlib, covering data manipulation, numerical computations, and visualization techniques. 📚 Learning Objectives This tutorial covers the fundamental concepts of Python data science using popular libraries like Pandas for…

← 뒤로

응답해 주셔서 감사합니다. ✨

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기