WeniVooks

검색

Cursor 톺아보기 with Python

여러 파일을 한 번에 관리하기 (@파일명 기능)

5.4 여러 파일을 한 번에 관리하기 (@파일명 기능)

🎯 오늘 배울 내용

지금까지는 하나의 파일에 모든 코드를 작성했다면, 이제 여러 파일로 나누어 관리하고 Cursor의 @파일명 기능으로 효율적으로 작업하는 방법을 배워보겠습니다!

📚 왜 여러 파일로 나누어야 할까?
현재 문제 상황

하나의 파일에 모든 코드:

# main.py (400줄짜리 파일)
print("=== 학생 관리 시스템 ===")
 
# 학생 데이터
students = {"김철수": 85, "이영희": 92, "박민수": 78}
 
# 학생 추가 기능
def add_student():
    name = input("학생 이름: ")
    score = int(input("점수: "))
    students[name] = score
    print(f"{name} 학생이 추가되었습니다.")
 
# 성적 조회 기능  
def view_scores():
    for name, score in students.items():
        print(f"{name}: {score}점")
 
# 통계 계산 기능
def calculate_stats():
    avg = sum(students.values()) / len(students)
    highest = max(students.values())
    print(f"평균: {avg:.1f}점, 최고점: {highest}점")
 
# ... 더 많은 기능들 ...
# (코드가 너무 길어짐!)
# main.py (400줄짜리 파일)
print("=== 학생 관리 시스템 ===")
 
# 학생 데이터
students = {"김철수": 85, "이영희": 92, "박민수": 78}
 
# 학생 추가 기능
def add_student():
    name = input("학생 이름: ")
    score = int(input("점수: "))
    students[name] = score
    print(f"{name} 학생이 추가되었습니다.")
 
# 성적 조회 기능  
def view_scores():
    for name, score in students.items():
        print(f"{name}: {score}점")
 
# 통계 계산 기능
def calculate_stats():
    avg = sum(students.values()) / len(students)
    highest = max(students.values())
    print(f"평균: {avg:.1f}점, 최고점: {highest}점")
 
# ... 더 많은 기능들 ...
# (코드가 너무 길어짐!)

문제점:

  • 📄 파일이 너무 길어져서 찾기 어려움
  • 🔧 수정할 때 다른 부분에 영향을 줄 위험
  • 👥 여러 사람이 동시에 작업하기 어려움
🔍 PART 1: 파일 분리하기
기능별로 파일 나누기

Chat에 질문:

큰 Python 프로그램을 여러 파일로 나누어 
관리하는 방법을 알려주세요.
큰 Python 프로그램을 여러 파일로 나누어 
관리하는 방법을 알려주세요.

파일 분리 예시:

프로젝트 폴더/
├── main.py          # 메인 실행 파일
├── students.py      # 학생 데이터 관리
├── calculator.py    # 성적 계산 기능  
└── display.py       # 화면 출력 기능
프로젝트 폴더/
├── main.py          # 메인 실행 파일
├── students.py      # 학생 데이터 관리
├── calculator.py    # 성적 계산 기능  
└── display.py       # 화면 출력 기능
🎯 실습 1: 학생 관리 시스템 분리하기

1단계: students.py 만들기

# students.py - 학생 데이터와 기본 관리 기능
 
# 학생 데이터 저장소
student_data = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78,
    "최지영": 95
}
 
def add_student(name, score):
    """학생 추가"""
    student_data[name] = score
    return f"{name} 학생이 추가되었습니다."
 
def remove_student(name):
    """학생 제거"""
    if name in student_data:
        del student_data[name]
        return f"{name} 학생이 제거되었습니다."
    else:
        return f"{name} 학생을 찾을 수 없습니다."
 
def get_student_score(name):
    """학생 점수 조회"""
    return student_data.get(name, None)
 
def get_all_students():
    """모든 학생 데이터 반환"""
    return student_data.copy()
# students.py - 학생 데이터와 기본 관리 기능
 
# 학생 데이터 저장소
student_data = {
    "김철수": 85,
    "이영희": 92,
    "박민수": 78,
    "최지영": 95
}
 
def add_student(name, score):
    """학생 추가"""
    student_data[name] = score
    return f"{name} 학생이 추가되었습니다."
 
def remove_student(name):
    """학생 제거"""
    if name in student_data:
        del student_data[name]
        return f"{name} 학생이 제거되었습니다."
    else:
        return f"{name} 학생을 찾을 수 없습니다."
 
def get_student_score(name):
    """학생 점수 조회"""
    return student_data.get(name, None)
 
def get_all_students():
    """모든 학생 데이터 반환"""
    return student_data.copy()

2단계: calculator.py 만들기

# calculator.py - 성적 계산 관련 기능
 
def calculate_average(scores):
    """평균 계산"""
    if not scores:
        return 0
    return sum(scores) / len(scores)
 
def find_highest_score(scores):
    """최고점 찾기"""
    if not scores:
        return 0
    return max(scores)
 
def find_lowest_score(scores):
    """최저점 찾기"""
    if not scores:
        return 0
    return min(scores)
 
def calculate_grade(score):
    """점수를 등급으로 변환"""
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    elif score >= 60:
        return 'D'
    else:
        return 'F'
 
def get_statistics(student_data):
    """전체 통계 계산"""
    if not student_data:
        return "데이터가 없습니다."
    
    scores = list(student_data.values())
    
    stats = {
        "총 학생 수": len(student_data),
        "평균 점수": calculate_average(scores),
        "최고 점수": find_highest_score(scores),
        "최저 점수": find_lowest_score(scores)
    }
    
    return stats
# calculator.py - 성적 계산 관련 기능
 
def calculate_average(scores):
    """평균 계산"""
    if not scores:
        return 0
    return sum(scores) / len(scores)
 
def find_highest_score(scores):
    """최고점 찾기"""
    if not scores:
        return 0
    return max(scores)
 
def find_lowest_score(scores):
    """최저점 찾기"""
    if not scores:
        return 0
    return min(scores)
 
def calculate_grade(score):
    """점수를 등급으로 변환"""
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    elif score >= 60:
        return 'D'
    else:
        return 'F'
 
def get_statistics(student_data):
    """전체 통계 계산"""
    if not student_data:
        return "데이터가 없습니다."
    
    scores = list(student_data.values())
    
    stats = {
        "총 학생 수": len(student_data),
        "평균 점수": calculate_average(scores),
        "최고 점수": find_highest_score(scores),
        "최저 점수": find_lowest_score(scores)
    }
    
    return stats

3단계: display.py 만들기

# display.py - 화면 출력 관련 기능
 
def show_title():
    """프로그램 제목 출력"""
    print("=" * 40)
    print("🎓 학생 관리 시스템")
    print("=" * 40)
 
def show_menu():
    """메뉴 출력"""
    print("\n📋 메뉴:")
    print("1. 학생 추가")
    print("2. 학생 제거")
    print("3. 점수 조회")
    print("4. 전체 학생 보기")
    print("5. 통계 보기")
    print("6. 종료")
 
def show_all_students(student_data):
    """모든 학생 출력"""
    if not student_data:
        print("등록된 학생이 없습니다.")
        return
    
    print("\n👥 전체 학생 목록:")
    for name, score in student_data.items():
        grade = calculate_grade(score)  # calculator.py에서 가져와야 함
        print(f"{name}: {score}점 ({grade}등급)")
 
def show_statistics(stats):
    """통계 정보 출력"""
    print(f"\n📊 통계 정보:")
    for key, value in stats.items():
        if isinstance(value, float):
            print(f"{key}: {value:.1f}")
        else:
            print(f"{key}: {value}")
# display.py - 화면 출력 관련 기능
 
def show_title():
    """프로그램 제목 출력"""
    print("=" * 40)
    print("🎓 학생 관리 시스템")
    print("=" * 40)
 
def show_menu():
    """메뉴 출력"""
    print("\n📋 메뉴:")
    print("1. 학생 추가")
    print("2. 학생 제거")
    print("3. 점수 조회")
    print("4. 전체 학생 보기")
    print("5. 통계 보기")
    print("6. 종료")
 
def show_all_students(student_data):
    """모든 학생 출력"""
    if not student_data:
        print("등록된 학생이 없습니다.")
        return
    
    print("\n👥 전체 학생 목록:")
    for name, score in student_data.items():
        grade = calculate_grade(score)  # calculator.py에서 가져와야 함
        print(f"{name}: {score}점 ({grade}등급)")
 
def show_statistics(stats):
    """통계 정보 출력"""
    print(f"\n📊 통계 정보:")
    for key, value in stats.items():
        if isinstance(value, float):
            print(f"{key}: {value:.1f}")
        else:
            print(f"{key}: {value}")

4단계: main.py 만들기

# main.py - 메인 실행 파일
 
# 다른 파일들에서 기능 가져오기
from students import *
from calculator import *
from display import *
 
def main():
    """메인 프로그램"""
    show_title()
    
    while True:
        show_menu()
        choice = input("\n선택하세요 (1-6): ")
        
        if choice == "1":
            # 학생 추가
            name = input("학생 이름: ")
            try:
                score = int(input("점수: "))
                result = add_student(name, score)
                print(result)
            except ValueError:
                print("올바른 점수를 입력해주세요.")
        
        elif choice == "2":
            # 학생 제거
            name = input("제거할 학생 이름: ")
            result = remove_student(name)
            print(result)
        
        elif choice == "3":
            # 점수 조회
            name = input("조회할 학생 이름: ")
            score = get_student_score(name)
            if score is not None:
                grade = calculate_grade(score)
                print(f"{name}: {score}점 ({grade}등급)")
            else:
                print(f"{name} 학생을 찾을 수 없습니다.")
        
        elif choice == "4":
            # 전체 학생 보기
            students = get_all_students()
            show_all_students(students)
        
        elif choice == "5":
            # 통계 보기
            students = get_all_students()
            stats = get_statistics(students)
            show_statistics(stats)
        
        elif choice == "6":
            print("프로그램을 종료합니다.")
            break
        
        else:
            print("올바른 메뉴를 선택해주세요.")
 
if __name__ == "__main__":
    main()
# main.py - 메인 실행 파일
 
# 다른 파일들에서 기능 가져오기
from students import *
from calculator import *
from display import *
 
def main():
    """메인 프로그램"""
    show_title()
    
    while True:
        show_menu()
        choice = input("\n선택하세요 (1-6): ")
        
        if choice == "1":
            # 학생 추가
            name = input("학생 이름: ")
            try:
                score = int(input("점수: "))
                result = add_student(name, score)
                print(result)
            except ValueError:
                print("올바른 점수를 입력해주세요.")
        
        elif choice == "2":
            # 학생 제거
            name = input("제거할 학생 이름: ")
            result = remove_student(name)
            print(result)
        
        elif choice == "3":
            # 점수 조회
            name = input("조회할 학생 이름: ")
            score = get_student_score(name)
            if score is not None:
                grade = calculate_grade(score)
                print(f"{name}: {score}점 ({grade}등급)")
            else:
                print(f"{name} 학생을 찾을 수 없습니다.")
        
        elif choice == "4":
            # 전체 학생 보기
            students = get_all_students()
            show_all_students(students)
        
        elif choice == "5":
            # 통계 보기
            students = get_all_students()
            stats = get_statistics(students)
            show_statistics(stats)
        
        elif choice == "6":
            print("프로그램을 종료합니다.")
            break
        
        else:
            print("올바른 메뉴를 선택해주세요.")
 
if __name__ == "__main__":
    main()
🔍 PART 2: Cursor @파일명 기능 활용
@파일명으로 여러 파일 참조하기

Chat에서 @파일명 사용법:

@students.py @calculator.py 
이 두 파일을 참고해서 새로운 기능을 추가해주세요.
학생의 등급별 통계를 보여주는 함수를 만들고 싶어요.
@students.py @calculator.py 
이 두 파일을 참고해서 새로운 기능을 추가해주세요.
학생의 등급별 통계를 보여주는 함수를 만들고 싶어요.

Cursor AI가 두 파일을 모두 이해하고 답변:

# calculator.py에 추가할 함수
def get_grade_statistics(student_data):
    """등급별 통계 계산"""
    grade_count = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0}
    
    for score in student_data.values():
        grade = calculate_grade(score)
        grade_count[grade] += 1
    
    return grade_count
 
# display.py에 추가할 함수  
def show_grade_distribution(grade_stats):
    """등급 분포 출력"""
    print(f"\n📈 등급별 분포:")
    total = sum(grade_stats.values())
    
    for grade, count in grade_stats.items():
        if total > 0:
            percentage = (count / total) * 100
            print(f"{grade}등급: {count}명 ({percentage:.1f}%)")
# calculator.py에 추가할 함수
def get_grade_statistics(student_data):
    """등급별 통계 계산"""
    grade_count = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0}
    
    for score in student_data.values():
        grade = calculate_grade(score)
        grade_count[grade] += 1
    
    return grade_count
 
# display.py에 추가할 함수  
def show_grade_distribution(grade_stats):
    """등급 분포 출력"""
    print(f"\n📈 등급별 분포:")
    total = sum(grade_stats.values())
    
    for grade, count in grade_stats.items():
        if total > 0:
            percentage = (count / total) * 100
            print(f"{grade}등급: {count}명 ({percentage:.1f}%)")
🎯 실습 2: @파일명으로 기능 확장하기

Chat 요청 예시들:

@main.py @students.py
메인 프로그램에 "학생 점수 수정" 기능을 추가해주세요.
@main.py @students.py
메인 프로그램에 "학생 점수 수정" 기능을 추가해주세요.
@calculator.py @display.py  
계산기 파일의 함수들을 사용해서 
화면 출력 파일에 "상위 3명 출력" 기능을 만들어주세요.
@calculator.py @display.py  
계산기 파일의 함수들을 사용해서 
화면 출력 파일에 "상위 3명 출력" 기능을 만들어주세요.
@students.py
학생 데이터를 파일에 저장하고 불러오는 기능을 추가해주세요.
@students.py
학생 데이터를 파일에 저장하고 불러오는 기능을 추가해주세요.
🔍 PART 3: 프로젝트 구조화
🎯 실습 3: 온라인 쇼핑몰 프로젝트 구조

프로젝트 구조:

쇼핑몰/
├── main.py           # 메인 실행
├── products.py       # 상품 관리
├── cart.py          # 장바구니 기능
├── order.py         # 주문 처리
└── utils.py         # 공통 유틸리티
쇼핑몰/
├── main.py           # 메인 실행
├── products.py       # 상품 관리
├── cart.py          # 장바구니 기능
├── order.py         # 주문 처리
└── utils.py         # 공통 유틸리티

products.py:

# products.py - 상품 관리
 
products_db = {
    "P001": {"name": "노트북", "price": 1200000, "stock": 10},
    "P002": {"name": "마우스", "price": 50000, "stock": 25},
    "P003": {"name": "키보드", "price": 120000, "stock": 15}
}
 
def get_product(product_id):
    """상품 정보 조회"""
    return products_db.get(product_id, None)
 
def get_all_products():
    """모든 상품 목록"""
    return products_db.copy()
 
def update_stock(product_id, quantity):
    """재고 업데이트"""
    if product_id in products_db:
        products_db[product_id]["stock"] -= quantity
        return True
    return False
# products.py - 상품 관리
 
products_db = {
    "P001": {"name": "노트북", "price": 1200000, "stock": 10},
    "P002": {"name": "마우스", "price": 50000, "stock": 25},
    "P003": {"name": "키보드", "price": 120000, "stock": 15}
}
 
def get_product(product_id):
    """상품 정보 조회"""
    return products_db.get(product_id, None)
 
def get_all_products():
    """모든 상품 목록"""
    return products_db.copy()
 
def update_stock(product_id, quantity):
    """재고 업데이트"""
    if product_id in products_db:
        products_db[product_id]["stock"] -= quantity
        return True
    return False

cart.py:

# cart.py - 장바구니 기능
 
user_cart = {}
 
def add_to_cart(product_id, quantity):
    """장바구니에 상품 추가"""
    if product_id in user_cart:
        user_cart[product_id] += quantity
    else:
        user_cart[product_id] = quantity
 
def remove_from_cart(product_id):
    """장바구니에서 상품 제거"""
    if product_id in user_cart:
        del user_cart[product_id]
        return True
    return False
 
def get_cart_total(products_db):
    """장바구니 총액 계산"""
    total = 0
    for product_id, quantity in user_cart.items():
        if product_id in products_db:
            price = products_db[product_id]["price"]
            total += price * quantity
    return total
 
def get_cart_items():
    """장바구니 내용 반환"""
    return user_cart.copy()
# cart.py - 장바구니 기능
 
user_cart = {}
 
def add_to_cart(product_id, quantity):
    """장바구니에 상품 추가"""
    if product_id in user_cart:
        user_cart[product_id] += quantity
    else:
        user_cart[product_id] = quantity
 
def remove_from_cart(product_id):
    """장바구니에서 상품 제거"""
    if product_id in user_cart:
        del user_cart[product_id]
        return True
    return False
 
def get_cart_total(products_db):
    """장바구니 총액 계산"""
    total = 0
    for product_id, quantity in user_cart.items():
        if product_id in products_db:
            price = products_db[product_id]["price"]
            total += price * quantity
    return total
 
def get_cart_items():
    """장바구니 내용 반환"""
    return user_cart.copy()
@파일명으로 통합 개발

Chat에서 여러 파일 참조:

@products.py @cart.py @utils.py
이 세 파일을 참고해서 main.py를 만들어주세요.
사용자가 상품을 둘러보고, 장바구니에 담고, 주문할 수 있는 
완전한 쇼핑 프로그램을 만들어주세요.
@products.py @cart.py @utils.py
이 세 파일을 참고해서 main.py를 만들어주세요.
사용자가 상품을 둘러보고, 장바구니에 담고, 주문할 수 있는 
완전한 쇼핑 프로그램을 만들어주세요.
🔍 PART 4: 실전 프로젝트 관리
🎯 실습 4: 게임 프로젝트 구조화

RPG 게임 프로젝트:

rpg_game/
├── main.py          # 게임 실행
├── player.py        # 플레이어 관리
├── monster.py       # 몬스터 관리  
├── battle.py        # 전투 시스템
├── inventory.py     # 인벤토리 관리
└── game_data.py     # 게임 데이터
rpg_game/
├── main.py          # 게임 실행
├── player.py        # 플레이어 관리
├── monster.py       # 몬스터 관리  
├── battle.py        # 전투 시스템
├── inventory.py     # 인벤토리 관리
└── game_data.py     # 게임 데이터

@파일명 활용 개발 과정:

  1. 기본 구조 설계:

    @game_data.py
    게임에 필요한 기본 데이터들을 정의해주세요.
    @game_data.py
    게임에 필요한 기본 데이터들을 정의해주세요.
  2. 플레이어 시스템:

    @game_data.py @player.py
    플레이어 클래스를 만들고 레벨업 시스템을 추가해주세요.
    @game_data.py @player.py
    플레이어 클래스를 만들고 레벨업 시스템을 추가해주세요.
  3. 전투 시스템:

    @player.py @monster.py @battle.py
    턴제 전투 시스템을 구현해주세요.
    @player.py @monster.py @battle.py
    턴제 전투 시스템을 구현해주세요.
  4. 통합 및 테스트:

    @player.py @monster.py @battle.py @inventory.py
    모든 시스템을 통합한 main.py를 만들어주세요.
    @player.py @monster.py @battle.py @inventory.py
    모든 시스템을 통합한 main.py를 만들어주세요.
💪 종합 실습: 카페 주문 관리 시스템

🎯 최종 프로젝트: 여러 파일로 구성된 완전한 시스템

프로젝트 구조:

cafe_system/
├── main.py          # 메인 프로그램
├── menu.py          # 메뉴 관리
├── order.py         # 주문 처리
├── customer.py      # 고객 관리
├── payment.py       # 결제 처리
├── report.py        # 매출 리포트
└── config.py        # 설정 파일
cafe_system/
├── main.py          # 메인 프로그램
├── menu.py          # 메뉴 관리
├── order.py         # 주문 처리
├── customer.py      # 고객 관리
├── payment.py       # 결제 처리
├── report.py        # 매출 리포트
└── config.py        # 설정 파일

Chat 활용 개발 과정:

1단계: @config.py
카페 기본 설정과 메뉴 데이터를 정의해주세요.

2단계: @config.py @menu.py  
메뉴 관리 기능을 만들어주세요.

3단계: @menu.py @order.py
주문 접수와 처리 기능을 만들어주세요.

4단계: @order.py @payment.py
결제 처리 시스템을 만들어주세요.

5단계: @order.py @payment.py @report.py
매출 분석 리포트 기능을 만들어주세요.

6단계: @menu.py @order.py @customer.py @payment.py @report.py
모든 기능을 통합한 메인 프로그램을 만들어주세요.
1단계: @config.py
카페 기본 설정과 메뉴 데이터를 정의해주세요.

2단계: @config.py @menu.py  
메뉴 관리 기능을 만들어주세요.

3단계: @menu.py @order.py
주문 접수와 처리 기능을 만들어주세요.

4단계: @order.py @payment.py
결제 처리 시스템을 만들어주세요.

5단계: @order.py @payment.py @report.py
매출 분석 리포트 기능을 만들어주세요.

6단계: @menu.py @order.py @customer.py @payment.py @report.py
모든 기능을 통합한 메인 프로그램을 만들어주세요.
🌟 이번 챕터에서 배운 것
파일 분리의 장점
  • 🗂️ 체계적 관리: 기능별로 파일 분리
  • 👥 협업 향상: 여러 사람이 동시 작업 가능
  • 🔧 유지보수: 특정 기능만 수정 가능
  • 🔄 재사용성: 다른 프로젝트에서 활용 가능
Cursor @파일명 기능
  • 📎 여러 파일 참조: @file1.py @file2.py
  • 🤖 AI 통합 이해: 여러 파일의 관계 파악
  • ⚡ 효율적 개발: 컨텍스트 유지하며 개발
  • 🔍 프로젝트 전체 이해: 구조를 파악한 답변
프로젝트 구조화
  • 📁 논리적 분류: 기능별 파일 분리
  • 🔗 모듈 연결: import로 기능 연결
  • 📝 명확한 책임: 각 파일의 역할 분담
  • 📈 확장성: 새로운 기능 추가 용이

💡 핵심 포인트:

  • 작은 단위로 나누어 관리하기
  • @파일명으로 AI와 효율적 소통하기
  • 체계적인 구조로 프로젝트 관리하기

🚀 다음 챕터 예고: Chapter 5.5에서는 코드 패턴 인식과 AI 고급 활용을 배워보겠습니다!

{"packages":["numpy","pandas","matplotlib","lxml"]}
5.3 내장 함수로 효율적인 코딩 - len, sum, max, min 등