Python 모듈과 표준 라이브러리
이 토픽을 마치면
import의 동작 원리를 이해하고, Python 표준 라이브러리의 핵심 모듈들을 활용할 수 있으며, pip로 외부 패키지를 설치하고 관리할 수 있습니다.
모듈이란
모듈은 Python 코드가 담긴 .py 파일 하나입니다. 함수, 클래스, 변수를 모아놓은 파일을 다른 파일에서 import해서 쓸 수 있습니다.
# math_utils.pydef add(a, b): return a + b
def multiply(a, b): return a * b
PI = 3.14159# main.pyimport math_utils
print(math_utils.add(3, 5)) # 8print(math_utils.multiply(4, 7)) # 28print(math_utils.PI) # 3.14159import math_utils를 하면 Python은 같은 디렉토리에서 math_utils.py를 찾아 실행하고, 그 안의 함수/변수를 math_utils.이름 형태로 사용할 수 있게 합니다.
import의 다양한 방식
# 1. 모듈 전체 가져오기import osos.getcwd() # 현재 디렉토리
# 2. 특정 함수만 가져오기from os.path import join, existsjoin("/home", "user") # '/home/user' — os.path.join 대신 join으로 쓸 수 있음
# 3. 별칭(alias) 붙이기import numpy as npnp.array([1, 2, 3]) # numpy.array 대신 np.array
# 4. 모든 것 가져오기 (비권장)from os import * # 이름 충돌 위험 — 어디서 왔는지 추적 불가from X import *는 편하지만, 이름이 어디서 왔는지 알 수 없어서 대규모 프로젝트에서는 쓰지 않습니다. 명시적 import가 항상 낫습니다.
표준 라이브러리 — 설치 없이 쓰는 도구들
Python을 설치하면 수백 개의 모듈이 함께 설치됩니다. 이것이 표준 라이브러리(Standard Library)입니다. "batteries included"라는 Python 철학을 반영합니다.
os — 운영체제와 상호작용
import os
# 현재 디렉토리print(os.getcwd()) # /home/user/project
# 파일 목록files = os.listdir(".")print(files) # ['main.py', 'data', 'output']
# 디렉토리 생성os.makedirs("output/reports", exist_ok=True)
# 환경 변수db_host = os.environ.get("DB_HOST", "localhost")os.path — 경로 처리
import os.path
path = "/home/user/data/report.csv"
os.path.basename(path) # 'report.csv'os.path.dirname(path) # '/home/user/data'os.path.splitext(path) # ('/home/user/data/report', '.csv')os.path.exists(path) # True or Falseos.path.join("data", "output", "file.txt") # 'data/output/file.txt'json — JSON 데이터 처리
import json
# Python 객체 → JSON 문자열data = {"name": "Hoon", "scores": [90, 85, 95]}json_str = json.dumps(data, ensure_ascii=False, indent=2)print(json_str)
# JSON 문자열 → Python 객체parsed = json.loads(json_str)print(parsed["name"]) # Hoon
# 파일에 저장/읽기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)ensure_ascii=False를 넣어야 한국어가 한글 같은 이스케이프 없이 그대로 저장됩니다.
datetime — 날짜와 시간
from datetime import datetime, timedelta
# 현재 시각now = datetime.now()print(now) # 2026-07-03 14:30:00.123456
# 포맷 변환print(now.strftime("%Y-%m-%d")) # 2026-07-03print(now.strftime("%Y/%m/%d %H:%M")) # 2026/07/03 14:30
# 문자열 → datetimedate = datetime.strptime("2026-07-03", "%Y-%m-%d")
# 날짜 계산tomorrow = now + timedelta(days=1)week_ago = now - timedelta(weeks=1)diff = datetime(2026, 12, 31) - nowprint(f"D-{diff.days}") # D-181collections — 고급 자료구조
from collections import Counter, defaultdict
# Counter — 빈도 세기words = ["apple", "banana", "apple", "cherry", "banana", "apple"]count = Counter(words)print(count) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})print(count.most_common(2)) # [('apple', 3), ('banana', 2)]
# defaultdict — 기본값 있는 딕셔너리scores = defaultdict(list)scores["math"].append(90)scores["math"].append(85)scores["english"].append(92)print(dict(scores)) # {'math': [90, 85], 'english': [92]}random — 난수 생성
import random
random.randint(1, 100) # 1~100 사이 정수random.choice(["A", "B", "C"]) # 목록에서 하나 선택random.shuffle([1, 2, 3, 4]) # 리스트를 제자리에서 섞음random.sample(range(100), 5) # 0~99에서 5개를 중복 없이 선택pip — 외부 패키지 설치
표준 라이브러리에 없는 기능은 외부 패키지로 설치합니다.
# 설치pip install requestspip install pandas numpy matplotlib
# 버전 지정 설치pip install requests==2.31.0
# 업그레이드pip install --upgrade requests
# 삭제pip uninstall requests
# 설치된 패키지 목록pip list
# requirements.txt로 의존성 관리pip freeze > requirements.txt # 현재 설치된 패키지 기록pip install -r requirements.txt # 기록된 패키지 일괄 설치requirements.txt는 프로젝트에서 사용하는 외부 패키지를 기록하는 파일입니다. 다른 사람(또는 서버)이 같은 환경을 재현할 수 있습니다.
name == "main" — 실행과 import 구분
# greet.pydef hello(name): print(f"Hello, {name}!")
if __name__ == "__main__": # 이 파일을 직접 실행할 때만 실행됨 hello("World")$ python greet.py # "Hello, World!" 출력# other.pyimport greet # hello("World")는 실행되지 않음greet.hello("Python") # "Hello, Python!" 출력python greet.py로 직접 실행하면 __name__이 "__main__"이 됩니다. 다른 파일에서 import greet로 가져오면 __name__이 "greet"이 됩니다. 이 패턴으로 "직접 실행 시의 테스트 코드"와 "모듈로 사용될 때의 기능"을 분리합니다.
핵심 정리
| 개념 | 정리 |
|---|---|
| 모듈 | .py 파일 하나 = 모듈 하나 |
import | 다른 파일의 코드를 가져옴 |
| 표준 라이브러리 | 설치 없이 바로 쓸 수 있는 모듈 모음 (os, json, datetime 등) |
pip | 외부 패키지 설치/관리 도구 |
requirements.txt | 프로젝트 의존성 기록 |
__name__ | 직접 실행 vs import 구분 |
Python의 강점 중 하나는 풍부한 표준 라이브러리와 거대한 서드파티 생태계(PyPI에 50만+ 패키지)입니다. "바퀴를 다시 발명하지 말라"는 원칙 — 직접 구현하기 전에 표준 라이브러리와 PyPI를 먼저 검색하는 습관이 생산성을 높입니다.
실전 패턴 — 여러 모듈을 조합하기
실무에서는 하나의 모듈만 쓰는 경우가 드뭅니다. 여러 표준 라이브러리를 조합하는 것이 일반적입니다.
import osimport jsonfrom datetime import datetime
def process_data_files(directory): results = [] for filename in os.listdir(directory): if not filename.endswith(".json"): continue filepath = os.path.join(directory, filename) with open(filepath, "r", encoding="utf-8") as f: data = json.load(f) results.append({ "file": filename, "records": len(data), "processed_at": datetime.now().strftime("%Y-%m-%d %H:%M") }) return results
# output:# [# {"file": "users.json", "records": 150, "processed_at": "2026-07-03 14:30"},# {"file": "orders.json", "records": 423, "processed_at": "2026-07-03 14:30"}# ]os로 파일을 탐색하고, json으로 읽고, datetime으로 시간을 기록 — 세 모듈이 자연스럽게 조합됩니다. 이런 패턴이 스크립트 작성의 기본입니다.