- Published on
8단계: 표준 라이브러리 활용
8-1. os 모듈
파일 시스템 경로, 환경변수, 디렉토리 작업 등을 처리합니다.
import os
print(os.getcwd())
print(os.listdir())
os.mkdir("sample_dir")
8-2. sys 모듈
파이썬 인터프리터와 관련된 정보를 다룹니다.
import sys
print(sys.argv)
print(sys.path)
sys.exit()
8-3. datetime 모듈
날짜와 시간 관련 작업에 사용됩니다.
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))
future = now + timedelta(days=7)
print(future)
8-4. math 모듈
수학 함수와 상수를 제공합니다.
import math
print(math.sqrt(16))
print(math.pi)
8-5. random 모듈
난수 생성, 리스트 섞기 등에 사용됩니다.
import random
print(random.randint(1, 10))
print(random.choice(["가", "나", "다"]))
random.shuffle([1, 2, 3, 4])
8-6. collections 모듈
고급 데이터 컨테이너들을 제공합니다.
from collections import Counter, defaultdict
cnt = Counter("banana")
print(cnt)
dd = defaultdict(int)
dd["a"] += 1
print(dd)
8-7. itertools 모듈
조합, 순열, 무한 반복 등 반복자 도구 제공
from itertools import permutations, cycle
print(list(permutations([1, 2, 3], 2)))
cyc = cycle(["A", "B", "C"])
for _ in range(5):
print(next(cyc))
8-8. pathlib 모듈
객체지향 방식으로 파일 경로 다루기
from pathlib import Path
p = Path("example.txt")
if p.exists():
print(p.read_text(encoding="utf-8"))
요약
- os, sys: 시스템과 환경 정보 처리
- datetime, math, random: 시간, 수학, 난수
- collections, itertools: 데이터 처리와 반복자 도구
- pathlib: 파일 경로를 객체로 안전하게 관리
심화학습
Q1. os.path과 pathlib의 차이점은 무엇인가요?
A1. os.path은 문자열 기반, pathlib은 객체 기반으로 경로를 처리하며, pathlib은 코드 가독성과 안정성이 더 뛰어납니다.
Q2. Counter와 defaultdict은 어떤 경우 유용하게 쓰이나요?
A2. 데이터 빈도 계산, 기본값이 필요한 딕셔너리 처리에 매우 유용합니다.
Q3. itertools.permutations는 어떤 상황에서 쓰일까요?
A3. 조합 알고리즘, 게임 시뮬레이션, 테스트 케이스 자동 생성 등에서 활용됩니다.