모듈과 패키지¶
Ⅴ 모듈, 패키지¶
01. 모듈이란?¶
모듈(Module)은 파이썬 코드를 담은 .py 파일입니다.
함수, 변수, 클래스를 파일 단위로 묶어 재사용할 수 있게 합니다.
my_project/
├── main.py ← 모듈을 사용하는 파일
└── math_utils.py ← 모듈 (함수들을 모아둔 파일)
모듈을 사용하는 이유¶
- 재사용: 같은 코드를 여러 파일에서 쓸 수 있음
- 정리: 관련 함수끼리 묶어서 관리
- 공유: 다른 사람이 만든 모듈도 가져다 쓸 수 있음
import 방법 3가지¶
# 방법 1: 모듈 전체 가져오기
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592...
# 방법 2: 특정 이름만 가져오기
from math import sqrt, pi
print(sqrt(16)) # 4.0 (math. 없이 바로 사용)
print(pi) # 3.141592...
# 방법 3: 별명(alias) 사용
import math as m
print(m.sqrt(16)) # 4.0
02. 모듈 만들기¶
직접 .py 파일을 만들면 모듈이 됩니다.
예시: calc.py 모듈 만들기¶
# calc.py
PI = 3.14159
def add(a, b):
return a + b
def multiply(a, b):
return a * b
def circle_area(r):
return PI * r * r
main.py에서 사용하기¶
# main.py
import calc
print(calc.add(3, 5)) # 8
print(calc.circle_area(2)) # 12.56636
# 또는 from으로 직접 가져오기
from calc import add, PI
print(add(10, 20)) # 30
print(PI) # 3.14159
if __name__ == "__main__": 패턴¶
# calc.py
def add(a, b):
return a + b
if __name__ == "__main__":
# 이 파일을 직접 실행할 때만 실행됨
# import로 가져올 때는 실행 안 됨
print(add(1, 2))
| 실행 방식 | __name__ 값 |
결과 |
|---|---|---|
python calc.py 직접 실행 |
"__main__" |
if 블록 실행 |
import calc |
"calc" |
if 블록 실행 안 됨 |
03. 패키지란?¶
패키지(Package)는 여러 모듈을 폴더로 묶은 것입니다.
폴더에 __init__.py 파일이 있으면 파이썬이 패키지로 인식합니다.
my_project/
├── main.py
└── utils/ ← 패키지 폴더
├── __init__.py ← 패키지임을 알려주는 파일 (비어있어도 됨)
├── string_utils.py
└── math_utils.py
패키지 사용 방법¶
# main.py
import utils.math_utils
print(utils.math_utils.add(3, 4))
# 또는
from utils.math_utils import add
print(add(3, 4))
# 또는
from utils import math_utils
print(math_utils.add(3, 4))
04. 여러 가지 모듈 활용하기¶
파이썬 표준 라이브러리에는 이미 많은 유용한 모듈이 있습니다.
math — 수학 함수¶
import math
print(math.sqrt(25)) # 5.0 — 제곱근
print(math.pi) # 3.141592653589793
print(math.floor(3.9)) # 3 — 내림
print(math.ceil(3.1)) # 4 — 올림
print(math.factorial(5))# 120 — 팩토리얼
print(math.log(100, 10))# 2.0 — 로그
random — 난수¶
import random
print(random.random()) # 0.0 이상 1.0 미만 실수
print(random.randint(1, 6)) # 1~6 사이 정수 (주사위)
print(random.choice(["a","b","c"])) # 리스트에서 하나 선택
random.shuffle([1,2,3,4,5]) # 리스트 순서 섞기
datetime — 날짜/시간¶
from datetime import datetime, date
now = datetime.now()
print(now) # 2026-05-23 10:30:00.000000
print(now.strftime("%Y년 %m월 %d일")) # 2026년 05월 23일
print(now.year, now.month, now.day) # 2026 5 23
today = date.today()
print(today) # 2026-05-23
os — 운영체제 관련¶
import os
print(os.getcwd()) # 현재 작업 디렉토리
print(os.listdir(".")) # 현재 폴더의 파일 목록
os.mkdir("new_folder") # 새 폴더 생성
print(os.path.exists("test.txt")) # 파일/폴더 존재 여부
print(os.path.join("data", "file.txt")) # 경로 합치기
sys — 시스템 관련¶
import sys
print(sys.version) # 파이썬 버전
print(sys.platform) # 운영체제 ('linux', 'win32', 'darwin')
sys.exit(0) # 프로그램 종료
json — JSON 처리¶
import json
# 딕셔너리 → JSON 문자열
data = {"name": "Alice", "age": 20, "scores": [90, 85]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON 문자열 → 딕셔너리
parsed = json.loads(json_str)
print(parsed["name"]) # Alice
# 파일에 저장
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 파일에서 읽기
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
실습 미션¶
미션 1: 모듈 만들기¶
1. converter.py 파일을 만들어 단위 변환 함수를 작성하세요.
- km_to_mile(km): km를 마일로 변환
- celsius_to_fahrenheit(c): 섭씨를 화씨로 변환
2. main.py에서 import하여 사용하세요.
미션 2: random 활용¶
1. random 모듈로 1~45 숫자 중 6개를 뽑는 로또 번호 생성기를 만드세요.
2. 중복 없이 정렬하여 출력하세요.
미션 3: datetime 활용¶
1. 오늘 날짜와 시간을 "YYYY년 MM월 DD일 HH시 MM분" 형식으로 출력하세요.
2. 내 생일까지 며칠이 남았는지 계산하세요.
미션 4 (심화): JSON 로그 저장¶
1. 사용자의 이름과 점수를 입력받아 JSON 파일에 저장하는 프로그램을 만드세요.
2. 프로그램을 다시 실행할 때 기존 데이터를 유지하고 추가하세요.
3. 모든 기록을 점수 순으로 출력하세요.
핵심 요약¶
| 개념 | 설명 |
|---|---|
| 모듈 | .py 파일 하나 = 함수/변수/클래스를 묶은 단위 |
import module |
모듈 전체 가져오기 |
from module import name |
특정 이름만 가져오기 |
import module as alias |
별명으로 가져오기 |
__name__ == "__main__" |
직접 실행 시에만 실행되는 코드 |
| 패키지 | 폴더 + __init__.py — 모듈의 모음 |
math |
수학 함수 (sqrt, pi, floor, ceil) |
random |
난수 생성 (random, randint, choice, shuffle) |
datetime |
날짜/시간 처리 |
json |
JSON 읽기/쓰기 |