프로그래밍 언어/Python

[Python] 디렉토리 만들기 (os.mkdir)

hanyoungyoo 2021. 3. 8. 13:42

파이썬으로 디렉토리를 만드는 함수인 os.mkdir의 사용법을 예제로 알아보려고 합니다.

 

아래 내용은 파이썬 공식 문서를 참고하여 작성하였습니다.

파이썬 file, directory 관련 공식 문서

한국어 공식 문서: docs.python.org/ko/3/library/filesys.html

 

파일과 디렉터리 액세스 — Python 3.9.2 문서

 

docs.python.org

영어 공식 문서: docs.python.org/3/library/os.html#os-file-dir

 

os — Miscellaneous operating system interfaces — Python 3.9.2 documentation

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, see the os.

docs.python.org

디렉토리를 만들기 위해서는 파이썬에서 제공하는 "os 모듈"을 사용해야합니다.

os 모듈은 운영 체제 인터페이스로 os와 관련된 기능들을 사용할 수 있게 해줍니다. 

대표적인 기능으로는 파일과 디렉토리 관리, 프로세스 관리, 스케쥴링 등이 있습니다.

 

예제를 통해 어떻게 사용하는 지 알아보도록 하겠습니다.

 

#현재 작업중인 디렉토리에 새로운 디렉토리를 만드는 방법

디렉토리의 경로를 다룰때는 os.path라는 모듈을 사용하는데요, 경로와 관련된 여러가지 유용한 기능들(절대주소, 상대주소 등)을 제공합니다. 

docs.python.org/3/library/os.path.html#module-os.path

 

import os

#현재 작업중인 디렉토리의 경로를 받아옵니다
current_working_directory = os.getcwd()
new_directory = "NEWDIR"

#현재 작업중인 디렉토리의 경로 + 만들고자 하는 디렉토리 이름
dir_path = os.path.join(current_working_directory, new_directory)

#디렉토리를 만듭니다.
os.mkdir(dir_path)

 

위와 같이 디렉토리를 만드는 함수는 아래와 같은 형식으로 호출해 줄 수 있습니다.

 

os.mkdir(path, mode=0o777, *, dir_fd=None)

 

os — Miscellaneous operating system interfaces — Python 3.9.2 documentation

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, see the os.

docs.python.org

 

여기까지가 파이썬으로 디렉토리를 만드는 법이었습니다. 보다 여러가지 예제들은 차차 추가할 예정이니, 혹시 궁금하신 부분은 문의 부탁드립니다:)