- 함수 + 변수 + 클래스를 모아놓은 파이썬 파일(*.py)
- 한번 만들어 놓으면 다른 파이썬 프로그램에서 불러와 사용 가능
- 코드 재사용성과 유지보수성 향상
| 장점 | 설명 |
|---|---|
| 코드 재사용 | 한 번 작성한 코드를 여러 프로그램에서 사용 |
| 네임스페이스 분리 | 함수명, 변수명 충돌 방지 |
| 유지보수 용이 | 기능별로 파일 분리하여 관리 |
| 협업 효율 | 팀원별로 모듈 분담 개발 가능 |
# mod0.py 파일 내용
myname = "hong" # 변수
def myFunc(*argc): # 함수
print(argc)
class MyClass: # 클래스
def __init__(self):
print('MyClass() 생성')# 터미널에서 모듈 파일 내용 확인
!cat mod0.py
# 모듈 파일 직접 실행
!python mod0.py현재 디렉토리의 모듈을 불러옵니다.
import mod0
# 모듈의 변수 호출
print(mod0.myname)
# 출력: 'hong'
# 모듈의 함수 호출
mod0.myFunc(10, 20, 30)
# 출력: (10, 20, 30)
# 모듈의 클래스 생성
my = mod0.MyClass()
# 출력: MyClass() 생성
print(my)
# 출력: <mod0.MyClass at 0x7d4ecd8ac6d0># 디렉토리 구조:
# 현재폴더/
# └── Mymodules/
# └── mod1.py
import Mymodules.mod1
# 모듈 사용
result = Mymodules.mod1.sum(10, 20)
print(result) # 30- 모듈 파일을 찾음 (현재 디렉토리 → sys.path 경로들)
- 모듈 코드를 컴파일 (
.pyc파일 생성) - 모듈 코드를 실행하여 객체 생성
- 모듈 네임스페이스에 바인딩
import sys
# 모듈 검색 경로 확인
print(sys.path)
# ['현재디렉토리', '/usr/lib/python3.x', ...]긴 모듈명을 짧은 이름으로 대체하여 사용합니다.
# 긴 모듈명
import Mymodules.mod1
Mymodules.mod1.sum(10, 20)
# 별칭 사용 (권장)
import Mymodules.mod1 as my
my.sum(10, 20)
# 출력: 50import numpy as np
import pandas as pd
import matplotlib.pyplot as plt모듈 이름을 매번 붙이지 않고 직접 사용할 수 있습니다.
# 기존 방식
import Mymodules.mod1
Mymodules.mod1.sum(55, 100)
# from import 사용
from Mymodules.mod1 import sum
sum(55, 100) # 모듈명 없이 직접 호출
# 출력: 155from mod0 import myname, myFunc
print(myname)
# 출력: 'hong'
myFunc(1, 2, 3)
# 출력: (1, 2, 3)from mod0 import myname as mn, myFunc as mf
print(mn)
# 출력: 'hong'
mf(1, 2, 3)
# 출력: (1, 2, 3)from mod0 import *
# 모듈의 모든 public 객체를 현재 네임스페이스로 가져옴
# 주의: 이름 충돌 위험, 코드 가독성 저하주의:
from module import *는 이름 충돌의 위험이 있고, 어떤 객체가 어디서 왔는지 추적하기 어려워 대규모 프로젝트에서는 사용을 권장하지 않습니다.
| 방식 | 예시 | 사용법 | 권장도 |
|---|---|---|---|
import 모듈 |
import math |
math.sqrt(4) |
O |
import 모듈 as 별칭 |
import numpy as np |
np.array([1,2]) |
O |
from 모듈 import 함수 |
from math import sqrt |
sqrt(4) |
O |
from 모듈 import * |
from math import * |
sqrt(4) |
X |
import numpy as np # 수치 계산
import pandas as pd # 데이터 분석
import matplotlib.pyplot as plt # 시각화
import tensorflow as tf # 딥러닝
import seaborn as sns # 통계 시각화| 모듈 | 관례적 별칭 | 용도 |
|---|---|---|
numpy |
np |
배열 및 수치 연산 |
pandas |
pd |
데이터프레임, 데이터 분석 |
matplotlib.pyplot |
plt |
데이터 시각화, 그래프 |
seaborn |
sns |
통계적 데이터 시각화 |
tensorflow |
tf |
딥러닝 프레임워크 |
sklearn |
(별칭 없음) | 머신러닝 |
scipy |
sp (덜 사용) |
과학 계산 |
cv2 |
(별칭 없음) | OpenCV, 이미지 처리 |
# TensorFlow/Keras
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Scikit-learn
from sklearn.model_selection import train_test_split, cross_validate
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_scoreCtrl + Space → 사용할 수 있는 함수나 클래스 보여줌
운영체제와 상호작용하기 위한 함수들을 제공합니다.
import osimport os
path = "/home/user/documents"
if os.path.exists(path):
print("경로가 존재합니다")
else:
print("경로가 존재하지 않습니다")import os
# 단일 디렉토리 생성
os.mkdir("new_folder")
# 이미 존재하면 에러 발생
# FileExistsError: [Errno 17] File exists: 'new_folder'import os
# 경로는 raw-string 사용 권장
savedir = r"tmpdir1/aaa/bbb/ccc"
if not os.path.exists(savedir):
os.makedirs(savedir) # 모든 상위 디렉토리도 함께 생성
print(savedir, '폴더 생성')
else:
print(savedir, "존재")
# exist_ok=True 사용 (이미 존재해도 에러 없음)
os.makedirs(savedir, exist_ok=True)import os
# 현재 디렉토리의 파일/폴더 목록
print(os.listdir('.'))
# ['file1.py', 'folder1', 'file2.txt', ...]
# 특정 디렉토리의 파일/폴더 목록
print(os.listdir('./sample_data'))
# ['data.csv', 'image.png', ...]import os
# 현재 작업 디렉토리 (Current Working Directory)
print(os.getcwd())
# /home/user/project
# 디렉토리 변경
os.chdir('/home/user/documents')
print(os.getcwd())
# /home/user/documentsimport os
# 경로 결합 (OS에 맞는 구분자 사용)
path = os.path.join('folder', 'subfolder', 'file.txt')
# Linux/Mac: folder/subfolder/file.txt
# Windows: folder\subfolder\file.txt
# 경로 분리
dirname = os.path.dirname('/home/user/file.txt') # /home/user
filename = os.path.basename('/home/user/file.txt') # file.txt
# 확장자 분리
name, ext = os.path.splitext('document.pdf')
print(name) # document
print(ext) # .pdf
# 절대 경로 변환
abs_path = os.path.abspath('file.txt')
print(abs_path) # /current/working/dir/file.txtimport os
# 파일인지 확인
print(os.path.isfile('file.txt')) # True/False
# 디렉토리인지 확인
print(os.path.isdir('folder')) # True/False
# 파일 크기 (바이트)
print(os.path.getsize('file.txt')) # 1024import os
# 환경 변수 조회
print(os.environ.get('HOME'))
# /home/user
# 환경 변수 설정
os.environ['MY_VAR'] = 'my_value'
# 모든 환경 변수 조회
print(os.environ)| 함수 | 설명 |
|---|---|
os.getcwd() |
현재 작업 디렉토리 |
os.chdir(path) |
디렉토리 변경 |
os.listdir(path) |
디렉토리 내용 목록 |
os.mkdir(path) |
디렉토리 생성 |
os.makedirs(path) |
중첩 디렉토리 생성 |
os.remove(path) |
파일 삭제 |
os.rmdir(path) |
빈 디렉토리 삭제 |
os.rename(src, dst) |
이름 변경/이동 |
os.path.exists(path) |
경로 존재 확인 |
os.path.isfile(path) |
파일인지 확인 |
os.path.isdir(path) |
디렉토리인지 확인 |
os.path.join(...) |
경로 결합 |
os.path.split(path) |
경로와 파일명 분리 |
os.path.splitext(path) |
파일명과 확장자 분리 |
os.path.abspath(path) |
절대 경로 변환 |
Shell Utility: 파일 및 디렉토리의 고수준 작업을 제공합니다.
import shutilimport shutil
# 파일 복사 (메타데이터 유지 안 함)
shutil.copy('source.txt', 'dest.txt')
# 파일 복사 (메타데이터 포함 - 권한, 수정 시간 등)
shutil.copy2('source.txt', 'dest.txt')
# 파일 복사 (파일 객체 사용)
with open('source.txt', 'rb') as src:
with open('dest.txt', 'wb') as dst:
shutil.copyfileobj(src, dst)import shutil
# 디렉토리 전체 복사 (재귀적)
shutil.copytree('source_dir', 'dest_dir')
# 이미 존재하는 경우 (Python 3.8+)
shutil.copytree('source_dir', 'dest_dir', dirs_exist_ok=True)import shutil
# 디렉토리 삭제 (내부 파일 포함)
shutil.rmtree('tmpdir2')
# 주의: 되돌릴 수 없음!
# 빈 디렉토리만 삭제 (os 모듈)
import os
os.rmdir('empty_folder') # 비어있지 않으면 에러import shutil
# 파일/디렉토리 이동
shutil.move('source.txt', 'new_location/source.txt')
# 이름 변경도 가능
shutil.move('old_name.txt', 'new_name.txt')import shutil
# 디스크 사용량 확인
total, used, free = shutil.disk_usage('/')
print(f"총 용량: {total // (2**30)} GB")
print(f"사용량: {used // (2**30)} GB")
print(f"남은 용량: {free // (2**30)} GB")| 함수 | 설명 |
|---|---|
shutil.copy(src, dst) |
파일 복사 |
shutil.copy2(src, dst) |
파일 복사 (메타데이터 포함) |
shutil.copytree(src, dst) |
디렉토리 복사 |
shutil.move(src, dst) |
이동/이름 변경 |
shutil.rmtree(path) |
디렉토리 삭제 (재귀) |
shutil.disk_usage(path) |
디스크 사용량 |
shutil.which(cmd) |
실행 파일 경로 찾기 |
파일 패턴 매칭을 위한 모듈입니다.
import globimport glob
# 모든 파일 불러오기
files = glob.glob('./sample_data/*')
print(files)
# ['./sample_data/data.csv', './sample_data/image.png', ...]
# 특정 확장자만 불러오기
csv_files = glob.glob('./sample_data/*.csv')
print(csv_files)
# ['./sample_data/data.csv', './sample_data/users.csv']
# 특정 패턴 매칭
py_files = glob.glob('./*.py')
print(py_files)
# ['./main.py', './utils.py', ...]import glob
# 모든 하위 디렉토리에서 검색 (Python 3.5+)
all_py_files = glob.glob('./**/*.py', recursive=True)
print(all_py_files)
# ['./main.py', './utils/helper.py', './tests/test_main.py', ...]| 패턴 | 설명 | 예시 |
|---|---|---|
* |
모든 문자 (0개 이상) | *.py → 모든 Python 파일 |
? |
단일 문자 | file?.txt → file1.txt, fileA.txt |
[...] |
문자 집합 | file[0-9].txt → file0.txt ~ file9.txt |
** |
모든 하위 디렉토리 | **/*.py → 모든 하위의 Python 파일 |
import glob
# 숫자로 시작하는 파일
glob.glob('[0-9]*.txt')
# a 또는 b로 시작하는 파일
glob.glob('[ab]*.py')
# 2자리 이름의 파일
glob.glob('??.txt')
# 특정 패턴 제외는 리스트 컴프리헨션과 함께
all_files = glob.glob('*.py')
filtered = [f for f in all_files if 'test' not in f]- 모듈의 묶음 (디렉토리)
- 관련된 모듈들을 하나의 폴더에 모아서 관리
__init__.py파일이 있으면 패키지로 인식 (Python 3.3+ 선택사항)
mypackage/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
├── __init__.py
└── module3.py
# 패키지의 모듈 import
import mypackage.module1
mypackage.module1.some_function()
# 별칭 사용
import mypackage.module1 as m1
m1.some_function()
# 특정 함수만 import
from mypackage.module1 import some_function
some_function()
# 하위 패키지의 모듈
from mypackage.subpackage import module3
module3.another_function()패키지 초기화 파일입니다.
# mypackage/__init__.py
# 패키지 레벨 변수
__version__ = '1.0.0'
# 패키지 import 시 자동 실행될 코드
print("mypackage가 로드되었습니다")
# 하위 모듈 자동 import
from .module1 import *
from .module2 import *
# __all__ 정의 (from package import * 시 사용)
__all__ = ['module1', 'module2']# 절대 import (권장)
from mypackage.module1 import function1
from mypackage.subpackage.module3 import function3
# 상대 import (패키지 내부에서만 사용)
# module2.py 에서
from .module1 import function1 # 같은 패키지
from ..otherpackage import module4 # 상위 패키지import sys
# Python 버전
print(sys.version)
# 3.9.7 (default, Sep 16 2021, ...)
# 최대 정수값
print(sys.maxsize)
# 9223372036854775807
# 모듈 검색 경로
print(sys.path)
# 명령행 인자
print(sys.argv)
# ['script.py', 'arg1', 'arg2']
# 프로그램 종료
sys.exit(0) # 정상 종료
sys.exit(1) # 에러로 종료import random
# 0.0 ~ 1.0 사이의 실수
print(random.random())
# 범위 내 정수
print(random.randint(1, 10)) # 1 이상 10 이하
# 범위 내 정수 (끝값 미포함)
print(random.randrange(1, 10)) # 1 이상 10 미만
# 리스트에서 무작위 선택
items = ['apple', 'banana', 'cherry']
print(random.choice(items))
# 여러 개 선택
print(random.sample(items, 2))
# 리스트 섞기
random.shuffle(items)
print(items)
# 시드 설정 (재현 가능한 랜덤)
random.seed(42)import math
# 상수
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# 올림, 내림, 반올림
print(math.ceil(4.3)) # 5
print(math.floor(4.7)) # 4
print(round(4.5)) # 4 (짝수 반올림)
# 제곱근
print(math.sqrt(16)) # 4.0
# 거듭제곱
print(math.pow(2, 3)) # 8.0
# 절대값
print(math.fabs(-5.5)) # 5.5
# 팩토리얼
print(math.factorial(5)) # 120
# 로그
print(math.log(10)) # 자연로그
print(math.log10(100)) # 상용로그 (2.0)
# 삼각함수
print(math.sin(math.pi / 2)) # 1.0
print(math.cos(0)) # 1.0from datetime import datetime, date, timedelta
# 현재 날짜/시간
now = datetime.now()
print(now) # 2024-01-15 14:30:45.123456
# 날짜만
today = date.today()
print(today) # 2024-01-15
# 특정 날짜/시간 생성
dt = datetime(2024, 12, 25, 10, 30, 0)
print(dt) # 2024-12-25 10:30:00
# 날짜 연산
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
# 포맷팅
print(now.strftime('%Y-%m-%d %H:%M:%S')) # 2024-01-15 14:30:45
print(now.strftime('%Y년 %m월 %d일')) # 2024년 01월 15일
# 파싱
dt = datetime.strptime('2024-01-15', '%Y-%m-%d')import json
# Python 객체 -> JSON 문자열
data = {'name': 'Alice', 'age': 25, 'cities': ['Seoul', 'Tokyo']}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON 문자열 -> Python 객체
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)| 모듈 | 용도 |
|---|---|
os |
운영체제 기능 (파일, 디렉토리, 환경변수) |
sys |
시스템 관련 (인자, 경로, 종료) |
shutil |
파일/디렉토리 고수준 작업 |
glob |
파일 패턴 매칭 |
pathlib |
객체지향 경로 처리 (Python 3.4+) |
math |
수학 함수 |
random |
난수 생성 |
datetime |
날짜/시간 처리 |
json |
JSON 인코딩/디코딩 |
re |
정규표현식 |
collections |
특수 컨테이너 (Counter, deque 등) |
itertools |
반복 도구 |
functools |
함수형 프로그래밍 도구 |