파이썬 os 모듈 심화 치트시트입니다. 디렉토리 순회, 파일 정보, 환경 변수, 프로세스 관리, 경로 처리 등 os 모듈의 핵심 기능을 최소 예제로 정리합니다.
os 모듈은 운영체제와 상호작용하는 기능을 제공합니다. 파일 시스템 조작, 환경 변수, 프로세스 정보 등을 다룹니다. 경로 처리는 pathlib을 권장하지만, os도 여전히 유용합니다.
언제 이 치트시트를 보나?
디렉토리 순회 (os.walk)가 필요할 때
환경 변수를 읽거나 설정할 때
프로세스 정보가 필요할 때
디렉토리 작업
1. 현재 디렉토리
1
2
3
4
5
6
7
8
9
importos# 현재 작업 디렉토리cwd=os.getcwd()print(cwd)# /home/user/project# 디렉토리 변경os.chdir('/tmp')print(os.getcwd())# /tmp
2. 디렉토리 목록
1
2
3
4
5
6
7
8
9
10
importos# 기본 목록 (이름만)entries=os.listdir('.')print(entries)# ['file.txt', 'subdir', ...]# scandir (더 효율적, 파일 정보 포함)withos.scandir('.')asentries:forentryinentries:print(f"{entry.name}: dir={entry.is_dir()}, file={entry.is_file()}")
3. 디렉토리 생성/삭제
1
2
3
4
5
6
7
8
9
10
11
12
13
importos# 단일 디렉토리 생성os.mkdir('new_dir')# 중첩 디렉토리 생성os.makedirs('path/to/nested',exist_ok=True)# 빈 디렉토리 삭제os.rmdir('new_dir')# 중첩 디렉토리 삭제 (빈 디렉토리만)os.removedirs('path/to/nested')
4. os.walk - 재귀 순회
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
importos# 모든 하위 파일/디렉토리 순회forroot,dirs,filesinos.walk('.'):print(f"\n디렉토리: {root}")print(f" 하위 디렉토리: {dirs}")print(f" 파일: {files}")# 특정 디렉토리 제외if'.git'indirs:dirs.remove('.git')# in-place 수정으로 순회 제외# 특정 확장자 파일만 찾기python_files=[]forroot,dirs,filesinos.walk('.'):forfinfiles:iff.endswith('.py'):python_files.append(os.path.join(root,f))
importospath='/home/user/documents/file.txt'# 경로 분해os.path.dirname(path)# '/home/user/documents'os.path.basename(path)# 'file.txt'os.path.split(path)# ('/home/user/documents', 'file.txt')# 확장자 분리os.path.splitext(path)# ('/home/user/documents/file', '.txt')# 경로 결합 (OS에 맞게)os.path.join('dir','subdir','file.txt')# 'dir/subdir/file.txt'# 절대 경로os.path.abspath('file.txt')# 정규화os.path.normpath('/home/user/../user/./file')# '/home/user/file'
환경 변수
9. 환경 변수 읽기/설정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
importos# 읽기home=os.environ.get('HOME')path=os.environ.get('PATH')# 기본값과 함께db_host=os.environ.get('DB_HOST','localhost')db_port=os.getenv('DB_PORT','5432')# 필수 환경 변수 (없으면 KeyError)api_key=os.environ['API_KEY']# 설정 (현재 프로세스만)os.environ['MY_VAR']='value'# 삭제delos.environ['MY_VAR']
10. 모든 환경 변수
1
2
3
4
5
6
7
8
importos# 딕셔너리처럼 사용forkey,valueinos.environ.items():print(f"{key}={value}")# 특정 접두사 필터db_vars={k:vfork,vinos.environ.items()ifk.startswith('DB_')}
importos# OS 이름print(os.name)# 'posix' (Linux/Mac) 또는 'nt' (Windows)# CPU 코어 수print(os.cpu_count())# 8# 터미널 크기try:size=os.get_terminal_size()print(f"터미널: {size.columns}x{size.lines}")exceptOSError:print("터미널 아님")
13. 프로세스 종료
1
2
3
4
5
6
7
8
9
10
11
importosimportsys# 정상 종료sys.exit(0)# 즉시 종료 (_exit은 cleanup 없음)os._exit(0)# 다른 프로세스에 시그널os.kill(pid,signal.SIGTERM)
유틸리티
14. 임시 파일 디렉토리
1
2
3
4
5
6
7
8
importosimporttempfile# 시스템 임시 디렉토리print(tempfile.gettempdir())# '/tmp' 또는 'C:\Users\...\Temp'# 또는print(os.environ.get('TMPDIR','/tmp'))
15. 파일 디스크립터
1
2
3
4
5
6
7
8
9
10
11
12
13
importos# 저수준 파일 열기fd=os.open('file.txt',os.O_RDONLY)content=os.read(fd,1024)os.close(fd)# 파이프r,w=os.pipe()os.write(w,b'hello')os.close(w)data=os.read(r,100)os.close(r)