
21. 모듈과 패키지 - 남이 만든 코드 활용하기
모든 것을 처음부터 만들 필요는 없다. 파이썬의 진짜 힘은 남이 만든 코드를 가져다 쓸 수 있다는 것이다.
import한 줄이면 수천 줄의 기능이 내 것이 된다.
모듈이란?
모듈(module)은 파이썬 코드가 들어있는 하나의 .py 파일이다.
- 변수, 함수, 클래스 등이 정의되어 있다
import로 불러와서 사용한다- 코드를 파일 단위로 정리하고 재사용하기 위한 도구
# math 모듈 불러오기
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4
print(math.floor(3.8)) # 3

import 방법 3가지
1. import 모듈
모듈 전체를 가져온다. 모듈.함수()로 사용한다.
import math
print(math.pi) # 3.14...
print(math.factorial(5)) # 120
2. from 모듈 import 이름
특정 함수나 변수만 가져온다. 모듈 이름 없이 바로 사용한다.
from math import pi, sqrt, factorial
print(pi) # 3.14...
print(sqrt(25)) # 5.0
print(factorial(5)) # 120
3. import 모듈 as 별명
모듈에 별명(alias)을 붙인다. 이름이 길 때 유용하다.
import datetime as dt
now = dt.datetime.now()
print(now) # 2026-02-21 15:30:45.123456
⚠️
from math import *는 모든 것을 가져오는 방법이지만, 이름 충돌 위험이 있어 권장하지 않는다.
# 비권장
from math import * # pi, sqrt, sin, cos... 전부 가져옴
# 어떤 함수가 어디서 온 건지 알 수 없음!
name과 main
파이썬 파일은 직접 실행하거나, 다른 파일에서 import해서 사용할 수 있다.
# my_module.py
def greet(name):
print(f"안녕하세요, {name}님!")
def add(a, b):
return a + b
# 직접 실행할 때만 동작하는 코드
if __name__ == "__main__":
print("이 파일을 직접 실행했습니다!")
greet("테스트")
print(add(3, 5))
# main.py
import my_module
my_module.greet("철수") # 안녕하세요, 철수님!
print(my_module.add(3, 5)) # 8
# "이 파일을 직접 실행했습니다!"는 출력되지 않음!
__name__은 파이썬이 자동으로 설정하는 변수- 직접 실행하면
__name__ == "__main__" - import하면
__name__ == "모듈이름"
표준 라이브러리 — 파이썬에 내장된 보물
파이썬은 배터리 포함(batteries included) 철학을 가지고 있다. 별도 설치 없이 사용할 수 있는 풍부한 표준 라이브러리가 있다.

os — 운영체제 관련
import os
# 현재 작업 디렉토리
print(os.getcwd())
# 디렉토리 목록
print(os.listdir("."))
# 경로 합치기
path = os.path.join("폴더", "파일.txt")
print(path) # 폴더\파일.txt (Windows) 또는 폴더/파일.txt (Mac/Linux)
# 파일 존재 확인
print(os.path.exists("test.py")) # True / False
# 환경 변수
print(os.environ.get("PATH"))
datetime — 날짜와 시간
from datetime import datetime, date, timedelta
# 현재 날짜/시간
now = datetime.now()
print(now) # 2026-02-21 15:30:00.123456
print(now.strftime("%Y년 %m월 %d일 %H:%M")) # 2026년 02월 21일 15:30
# 오늘 날짜
today = date.today()
print(today) # 2026-02-21
print(today.year) # 2026
print(today.month) # 2
print(today.weekday()) # 5 (0=월, 6=일)
# 날짜 계산
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
print(f"내일: {tomorrow}")
print(f"다음주: {next_week}")
# 생일까지 남은 날
birthday = date(2026, 12, 25)
diff = birthday - today
print(f"크리스마스까지 {diff.days}일!")
math — 수학 함수
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.sqrt(144)) # 12.0
print(math.pow(2, 10)) # 1024.0
print(math.log(100, 10)) # 2.0
print(math.factorial(10)) # 3628800
print(math.gcd(12, 8)) # 4 (최대공약수)
print(math.ceil(3.1)) # 4 (올림)
print(math.floor(3.9)) # 3 (내림)
random — 난수 생성
import random
# 정수 난수
print(random.randint(1, 100)) # 1~100 사이 랜덤
# 실수 난수
print(random.random()) # 0.0 ~ 1.0 사이
# 리스트에서 랜덤 선택
fruits = ["사과", "바나나", "체리", "딸기"]
print(random.choice(fruits)) # 랜덤 1개
print(random.sample(fruits, 2)) # 랜덤 2개 (중복 없이)
# 리스트 섞기
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers) # [3, 1, 5, 2, 4] (매번 다름)
collections — 고급 자료구조
from collections import Counter, defaultdict
# Counter: 요소 개수 세기
colors = ["red", "blue", "red", "green", "blue", "red"]
count = Counter(colors)
print(count) # Counter({'red': 3, 'blue': 2, 'green': 1})
print(count.most_common(2)) # [('red', 3), ('blue', 2)]
# defaultdict: 기본값이 있는 딕셔너리
scores = defaultdict(list)
scores["수학"].append(90)
scores["수학"].append(85)
scores["영어"].append(88)
print(dict(scores)) # {'수학': [90, 85], '영어': [88]}
json — JSON 처리
import json
# 딕셔너리 → JSON 문자열
data = {"name": "김철수", "age": 25, "scores": [85, 92, 78]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON 문자열 → 딕셔너리
parsed = json.loads(json_str)
print(parsed["name"]) # 김철수
pip — 외부 패키지 설치
pip는 파이썬의 패키지 관리자다. 전 세계 개발자들이 만든 패키지를 설치할 수 있다.
기본 명령어
# 패키지 설치
pip install requests
# 특정 버전 설치
pip install requests==2.31.0
# 패키지 업그레이드
pip install --upgrade requests
# 패키지 삭제
pip uninstall requests
# 설치된 패키지 목록
pip list
# 패키지 정보
pip show requests
자주 쓰는 외부 패키지
# requests - HTTP 요청 (웹 데이터 가져오기)
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200
print(response.json()) # JSON 데이터
# 데이터 분석 삼대장 (설치 필요)
# pip install numpy pandas matplotlib
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
requirements.txt
프로젝트에 필요한 패키지 목록을 파일로 관리한다.
# 현재 설치된 패키지 목록 저장
pip freeze > requirements.txt
# requirements.txt로 한 번에 설치
pip install -r requirements.txt
자기만의 모듈 만들기
# utils.py (내가 만든 모듈)
def add(a, b):
"""두 수의 합"""
return a + b
def is_even(n):
"""짝수인지 확인"""
return n % 2 == 0
PI = 3.14159
if __name__ == "__main__":
print(add(3, 5)) # 테스트용
print(is_even(4))
# main.py
from utils import add, is_even, PI
print(add(10, 20)) # 30
print(is_even(7)) # False
print(PI) # 3.14159
직접 해보기
문제 1. math 모듈을 사용해서 원의 넓이를 구하는 circle_area(radius) 함수를 만들어보자. (공식: pi * r^2)
문제 2. datetime을 사용해서 오늘 날짜를 "2026년 02월 21일 (토)" 형식으로 출력해보자.
문제 3. random을 사용해서 로또 번호(1~45 중 6개, 중복 없이)를 생성해보자. 정렬해서 출력.
문제 4. collections.Counter를 사용해서 문장에서 가장 많이 나온 단어 3개를 찾아보자.
문제 5. json 모듈로 딕셔너리를 JSON 문자열로 변환하고, 다시 딕셔너리로 변환해보자.
정답 보기
# 문제 1
import math
def circle_area(radius):
return math.pi * radius ** 2
print(f"반지름 5인 원의 넓이: {circle_area(5):.2f}")
# 반지름 5인 원의 넓이: 78.54
# 문제 2
from datetime import date
today = date.today()
days_kr = ["월", "화", "수", "목", "금", "토", "일"]
day_name = days_kr[today.weekday()]
print(f"{today.year}년 {today.month:02d}월 {today.day:02d}일 ({day_name})")
# 문제 3
import random
lotto = sorted(random.sample(range(1, 46), 6))
print(f"로또 번호: {lotto}")
# 문제 4
from collections import Counter
text = "파이썬 파이썬 자바 파이썬 자바 코틀린 자바스크립트 파이썬 자바"
words = text.split()
counter = Counter(words)
print("가장 많은 단어 3개:")
for word, count in counter.most_common(3):
print(f" {word}: {count}번")
# 문제 5
import json
data = {"이름": "김철수", "나이": 25, "취미": ["독서", "게임"]}
# 딕셔너리 → JSON 문자열
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON 문자열 → 딕셔너리
parsed = json.loads(json_str)
print(f"이름: {parsed['이름']}, 나이: {parsed['나이']}")
오늘의 정리
| 항목 | 내용 |
|---|---|
| import | import 모듈 → 모듈.함수()로 사용 |
| from...import | from 모듈 import 함수 → 바로 사용 |
| as | import 모듈 as 별명 → 짧은 이름으로 사용 |
| __name__ | 직접 실행 시 "__main__", import 시 모듈 이름 |
| 표준 라이브러리 | os, datetime, math, random, json, collections 등 |
| pip | pip install 패키지로 외부 패키지 설치 |
| requirements.txt | 프로젝트 패키지 목록 관리 파일 |
다음 편 예고: 에러와 예외처리 - 프로그램이 죽지 않게
프로그램은 예상치 못한 상황에서 에러를 만난다. try/except로 에러를 잡아서 처리하는 방법, 그리고 직접 에러를 만드는 raise까지 알아보자.
태그: 파이썬 Python 파이썬독학 모듈 import 패키지 pip 표준라이브러리 파이썬기초 IT교육
'Python' 카테고리의 다른 글
| 23. 파일 읽기/쓰기 - 데이터를 저장하자 (0) | 2026.02.22 |
|---|---|
| 22. 에러와 예외처리 - 프로그램이 죽지 않게 (0) | 2026.02.22 |
| 20. 데코레이터와 제너레이터 - 중급으로 가는 관문 (1) | 2026.02.22 |
| 19. 재귀 함수 - 자기 자신을 호출하는 함수 (0) | 2026.02.22 |
| 18. 함수 (2) - 스코프와 고급 기능 (0) | 2026.02.22 |
댓글