본문으로 건너뛰기

[Python] 파일, 디렉토리 존재 여부 확인

파이썬의 os.path, pathlib 라이브러리에서 제공하는 함수들을 이용하여 파일 또는 디렉토리 존재 여부를 확인할 수 있습니다.

예제와 함께 사용 방법을 알아보겠습니다.

1. os.path 라이브러리 : isdir(), isfile()

os.path는 isdir(), isfile() 함수를 제공합니다.

  • isdir(): 인자로 전달된 경로가 존재하고, 폴더일 때 True를 리턴. 파일 또는 존재하지 않을 때 False 리턴
  • isfile(): 인자로 전달된 경로가 존재하고, 파일일 때 True를 리턴. 폴더 또는 존재하지 않을 때 False 리턴
import os

my_dir_path = "/home/mjs/tests"
my_file_path = "/home/mjs/tests/test1.txt"

print(os.path.isdir(my_dir_path)) // True
print(os.path.isdir(my_file_path)) // False

print(os.path.isfile(my_dir_path)) // False
print(os.path.isfile(my_file_path)) // True

실행 결과:

True
False
False
True

2. pathlib 라이브러리 : is_dir(), is_file()

pathlib도 is_dir(), is_file() 함수를 지원합니다.

  • is_dir(): 인자로 전달된 경로가 존재하고, 폴더일 때 True를 리턴. 파일 또는 존재하지 않을 때 False 리턴
  • is_file(): 인자로 전달된 경로가 존재하고, 파일일 때 True를 리턴. 폴더 또는 존재하지 않을 때 False 리턴 추가로, exists()를 지원하는데, 인자로 전달된 경로가 존재하면 True를 리턴합니다. 파일인지 폴더인지는 고려하지 않습니다.
from pathlib import Path

my_dir_path = Path("/home/mjs/tests")
my_file_path = Path("/home/mjs/tests/test1.txt")

print(my_dir_path.exists()) # True
print(my_file_path.exists()) # True

print(my_dir_path.is_dir()) # True
print(my_file_path.is_dir()) # False

print(my_dir_path.is_file()) # False
print(my_file_path.is_file()) # True

실행 결과:

True
True
True
False
False
True