Python에서 디렉터리를 손쉽게 생성하기: mkdir vs makedirs

1. Introduction

Python을 사용하면 파일과 디렉터리를 손쉽게 관리할 수 있습니다. 특히 디렉터리를 생성하는 것은 파일을 정리하고 백업하며 자동으로 생성하는 가장 일반적인 작업 중 하나입니다. 이 가이드는 os 모듈과 pathlib 모듈을 이용한 디렉터리 생성 방법을 자세히 설명합니다. 또한 재귀적 디렉터리 생성과 오류 처리에 대해서도 다루며, Python 초보자도 이해하기 쉽도록 구성되었습니다.

2. Creating Directories Using os.mkdir()

Basic Usage

os.mkdir()는 지정된 경로에 단일 디렉터리를 생성하는 기본적인 방법입니다. 하지만 이 함수는 상위 디렉터리가 존재하지 않을 경우 오류를 발생시킨다는 제한이 있습니다. 아래 코드는 간단한 디렉터리 생성 방법을 보여줍니다.

import os

# Specify the path of the directory to create
dir_path = './new_directory'

# Create the directory
os.mkdir(dir_path)

이 코드를 실행하면 지정된 경로에 디렉터리가 생성되지만, 동일한 이름의 디렉터리가 이미 존재하면 FileExistsError가 발생합니다. 이는 os.mkdir() 사용 시 유의해야 할 점입니다.

Error Handling

디렉터리를 생성하기 전에 이미 존재하는지 확인하면 오류를 방지할 수 있습니다. 다음 코드는 그 예시입니다.

import os

# Specify the path of the directory to create
dir_path = './new_directory'

# Check whether the directory exists
if not os.path.exists(dir_path):
    os.mkdir(dir_path)
else:
    print(f"The directory '{dir_path}' already exists.")

이 방법을 사용하면 이미 존재하는 디렉터리를 실수로 다시 만들려고 할 때 발생하는 오류를 피할 수 있습니다.

年収訴求

3. Recursive Directory Creation Using os.makedirs()

Recursive Directory Creation

os.makedirs()os.mkdir()의 상위 개념이라고 볼 수 있습니다. 한 번에 여러 단계의 디렉터리를 생성할 수 있기 때문에, 상위 디렉터리가 없어도 중간 디렉터리를 자동으로 만들 수 있습니다.

import os

# Path including intermediate directories
dir_path = './parent_directory/sub_directory'

# Create directories recursively
os.makedirs(dir_path)

이 예시에서는 parent_directory와 그 안의 sub_directory가 한 번에 생성됩니다. 중간 디렉터리가 존재하지 않아도 모든 디렉터리를 오류 없이 생성할 수 있다는 점이 큰 편리함을 보여줍니다.

Error Handling Using exist_ok=True

os.makedirs()에는 exist_ok 옵션이 있어, 디렉터리가 이미 존재하더라도 오류를 발생시키지 않고 진행할 수 있습니다.

import os

dir_path = './parent_directory/sub_directory'

# Do not raise an error even if the directory already exists
os.makedirs(dir_path, exist_ok=True)

이 방법을 사용하면 사전에 디렉터리 존재 여부를 확인할 필요가 없어져 오류 처리가 간단해집니다.

4. Creating Directories with the pathlib Module

Creating Directories Using Path Objects

pathlib 모듈은 Python 3.4 이후부터 사용할 수 있는 파일 시스템 경로 작업을 위한 편리한 모듈입니다. Path() 객체를 사용하면 코드 가독성이 향상됩니다.

from pathlib import Path

# Specify the directory path
dir_path = Path('./new_directory')

# Create the directory
dir_path.mkdir()

pathlib의 장점은 객체 지향 방식으로 경로를 조작할 수 있어 코드가 직관적이라는 점입니다.

Recursive Directory Creation and Error Handling

pathlib을 사용한 재귀적 디렉터리 생성도 옵션만 지정하면 손쉽게 구현할 수 있습니다.

from pathlib import Path

# Path including intermediate directories
dir_path = Path('./parent_directory/sub_directory')

# Create including intermediate directories
dir_path.mkdir(parents=True, exist_ok=True)

이 코드에서는 중간 디렉터리를 포함한 여러 단계의 디렉터리를 한 번에 생성하며, 디렉터리가 이미 존재해도 오류가 발생하지 않습니다.

5. Checking Directory Existence and Error Handling

Verifying whether a directory already exists is a fundamental part of error handling. os module and pathlib to check for a directory’s existence and safely perform directory operations.

os 모듈을 사용한 확인 방법

import os

dir_path = './new_directory'

if os.path.exists(dir_path):
    print(f"Directory '{dir_path}' already exists.")
else:
    print(f"Directory '{dir_path}' does not exist.")

pathlib을 사용한 확인 방법

from pathlib import Path

dir_path = Path('./new_directory')

if dir_path.exists():
    print(f"Directory '{dir_path}' already exists.")
else:
    print(f"Directory '{dir_path}' does not exist.")

6. 요약

이 글에서는 Python을 사용하여 디렉터리를 생성하는 다양한 방법에 대해 자세히 설명했습니다. os.mkdir()os.makedirs()의 차이점, 재귀적인 디렉터리 생성 및 오류 처리 방법을 배웠습니다. 또한 Python의 최신 표준 모듈인 pathlib을 사용하면 코드가 더 간단하고 가독성이 높아진다는 것을 알게 되었습니다.

사용 사례에 가장 적합한 방법을 선택하고 효율적인 디렉터리 작업을 수행하세요.