https://docs.python.org/ko/3/library/os.html
os — Miscellaneous operating system interfaces
Source code: Lib/os.py This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, s...
docs.python.org
os 모듈 패키지 임포트
import os
현재 작업 디렉터리를 문자열로 반환
os.getcwd()
작업 디렉터리를 path로 변경
os.chdir(dir_path)
path에 있는 항목들의 이름을 담고 있는 리스트를 리턴
os.listdir(dir_path)
임의의 순서로 나열
디렉터리 생성1
os.mkdir(dir_path, mode=0o777, *, dir_fd=None)
이미 디렉터리가 존재하면, FileExistsError 발생
상위 디렉터리 경로가 존재하지 않으면 FileNotFoundError 발생
디렉터리 생성2
os.makedirs(dir_path, mode=0o777, exist_ok=False)
디렉터리뿐만아니라 상위 디렉터리가 없다면 만든다
exist_ok가 False: 이미 디렉터리가 존재하면, FileExistsError 발생
중간에 bb 디렉터리가 없을 때 mkdir
중간에 bb 디렉터리가 없을 때 makedirs
파일 삭제
os.remove(file_path, *, dir_fd=None)
path가 디렉터리면 OSError
파일이 없으면 FileNotFoundError
사용중인 파일을 제거하려고 하면 예외 발생
비어있는 디렉터리 삭제
os.rmdir(dir_path, *, dir_fd=None)
디렉터리가 존재하지 않는다면 FileNotFoundError
디렉터리가 비어있지 않다면 OSError 발생
비어있지 않은 디렉터리를 삭제
import shutil
shutil.rmtree(dir_path)
os.path 모듈
https://docs.python.org/ko/3/library/os.path.html#os.path.isfile
os.path — Common pathname manipulations
Source code: Lib/genericpath.py, Lib/posixpath.py(for POSIX) and Lib/ntpath.py(for Windows). This module implements some useful functions on pathnames. To read or write files see open(), and for ac...
docs.python.org
path가 존재 여부 확인하여 bool 값을 리턴
os.path.exists(path)
파일인지 디렉터리인지 확인하여 bool 값을 리턴
# path가 존재하는 파일이면 True 반환
os.path.isfile(path)
# path가 존재하는 디렉터리이면 True 반환
os.path.isdir(path)
path들을 연결하여 문자열로 리턴
os.path.join(path, *paths)
디렉터리 만들기
# 디렉터리가 존재하지 않는다면
if not os.path.exists(dir_path):
# 디렉터리 생성
os.makedirs(dir_path)
디렉터리 내 특정 확장자만 리턴
# jpg/png/json/xml 등
[file for file in os.lisdir(dir_path) if file.endswith('.확장자명')]
후에 추가 예정
'Python' 카테고리의 다른 글
[VSCode] ipynb 사용하기 (0) | 2024.07.19 |
---|---|
[Python] 가상환경 오류 프로파일링 (0) | 2024.07.08 |
[Python] Lambda Expressions (0) | 2024.06.26 |
[Python] map filter reduce (0) | 2024.06.25 |
[Python] List methods (0) | 2024.06.24 |