학습 목표

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

검색 및 삭제 기능 추가

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에서 더 알아보기

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

댓글 남기기

  • Mastering CSS Grid and Flexbox for Responsive Web Design

    [Tutorial] · 2026-05-06 02:31 UTC Mastering CSS Grid and Flexbox for Responsive Web Design 💡 TL;DR Understand the fundamentals of CSS Grid and Flexbox, including layout models and responsive design, to build robust and adaptable web applications. 📚 Learning Objectives This tutorial introduces the basics of CSS Grid and Flexbox, covering layout models, box sizing,…

  • Complete Guide to HTML5 Forms and Validation

    [Tutorial] · 2026-05-06 01:29 UTC Complete Guide to HTML5 Forms and Validation 💡 TL;DR Master HTML5 forms and validation to build accessible and functional web applications. 📚 Learning Objectives This tutorial covers the basics of HTML5 forms, including validation, semantic attributes, and accessibility features. Learn how to create robust and user-friendly forms that meet modern…

  • Building a Simple Web Application with React

    [Tutorial] · 2026-05-06 00:27 UTC Building a Simple Web Application with React 💡 TL;DR Learn how to build a basic web application with React using components, state management, and routing. 📚 Learning Objectives This tutorial covers the basics of creating a simple web application with React, including components, state management, and routing. Learners will gain…

  • C++ Template Metaprogramming for Beginners

    [Tutorial] · 2026-05-05 23:24 UTC C++ Template Metaprogramming for Beginners 💡 TL;DR Master C++ template metaprogramming to perform compile-time calculations and optimize your code. 📚 Learning Objectives Learn how to master C++ template metaprogramming, a powerful technique for performing compile-time calculations. This guide covers its benefits, key concepts, and practical examples to help you get…

  • Understanding Pointers and Memory Management in C++

    [Tutorial] · 2026-04-30 05:10 UTC Understanding Pointers and Memory Management in C++ 💡 TL;DR Mastering pointers in C++ is crucial for efficient memory management and writing effective code. 📚 Learning Objectives This tutorial covers the fundamentals of pointers in C++, including declaration, initialization, and memory management. Students will learn how to effectively use pointers to…

← 뒤로

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

TechTinkerer's에서 더 알아보기

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

계속 읽기

TechTinkerer's에서 더 알아보기

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

계속 읽기