Python 에서 경로가 디렉토리인지 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 에서 경로가 디렉토리인지 확인하는 방법을 배우게 됩니다. 이는 os.path 모듈을 사용하여 파일과 디렉토리를 구별하는 과정을 포함합니다.

먼저 디렉토리와 파일을 생성한 다음, os.path.isfile()os.path.isdir()를 사용하여 이를 식별하는 것으로 시작합니다. 그런 다음 랩은 os.path.isdir()에 초점을 맞춰 다양한 경로 유형에 따른 동작을 살펴보고, Python 에서 디렉토리 존재 여부를 확인하는 방법에 대한 실질적인 이해를 제공합니다.

파일과 디렉토리 구별하기

이 단계에서는 Python 을 사용하여 파일과 디렉토리를 구별하는 방법을 배우게 됩니다. 이는 모든 Python 프로그래머에게 기본적인 기술이며, 파일 시스템과 견고하고 신뢰할 수 있는 방식으로 상호 작용하는 프로그램을 작성할 수 있게 해줍니다.

시작하기 위해 ~/project 디렉토리에 디렉토리와 파일을 생성해 보겠습니다. WebIDE 를 열고 터미널을 엽니다.

먼저 my_directory라는 디렉토리를 생성합니다.

mkdir my_directory

다음으로, my_file.txt라는 빈 파일을 생성합니다.

touch my_file.txt

이제 디렉토리와 파일이 있으므로 Python 을 사용하여 어느 것이 무엇인지 확인할 수 있습니다.

WebIDE 의 코드 편집기를 열고 ~/project 디렉토리에 check_type.py라는 새 파일을 생성합니다. 파일에 다음 코드를 추가합니다.

import os

file_path = "my_file.txt"
directory_path = "my_directory"

if os.path.isfile(file_path):
    print(f"{file_path} is a file")
else:
    print(f"{file_path} is not a file")

if os.path.isdir(directory_path):
    print(f"{directory_path} is a directory")
else:
    print(f"{directory_path} is not a directory")

이 코드는 os.path.isfile()os.path.isdir() 함수를 사용하여 주어진 경로가 각각 파일인지 디렉토리인지 확인합니다.

check_type.py 파일을 저장합니다.

이제 터미널에서 스크립트를 실행합니다.

python check_type.py

다음과 같은 출력을 볼 수 있습니다.

my_file.txt is a file
my_directory is a directory

이는 Python 스크립트가 my_file.txt를 파일로, my_directory를 디렉토리로 올바르게 식별함을 확인합니다.

os.path.isdir() 로 테스트하기

이전 단계에서는 os.path.isfile()os.path.isdir()를 모두 사용하여 파일과 디렉토리를 구별하는 방법을 배웠습니다. 이 단계에서는 os.path.isdir()에 초점을 맞춰 다양한 유형의 경로에 따른 동작을 살펴보겠습니다.

Python 의 os.path 모듈에 있는 os.path.isdir() 함수는 주어진 경로가 기존 디렉토리를 참조하는지 확인하는 데 사용됩니다. 경로가 디렉토리이면 True를 반환하고, 그렇지 않으면 False를 반환합니다. 이 함수는 특정 경로가 디렉토리별 작업을 수행하기 전에 디렉토리를 가리키는지 확인해야 할 때 특히 유용합니다.

이전 단계에서 생성한 check_type.py 파일을 수정하여 os.path.isdir()에만 집중해 보겠습니다. WebIDE 의 코드 편집기에서 check_type.py를 열고 내용을 다음과 같이 변경합니다.

import os

directory_path = "my_directory"
file_path = "my_file.txt"
nonexistent_path = "nonexistent_directory"

if os.path.isdir(directory_path):
    print(f"{directory_path} is a directory")
else:
    print(f"{directory_path} is not a directory")

if os.path.isdir(file_path):
    print(f"{file_path} is a directory")
else:
    print(f"{file_path} is not a directory")

if os.path.isdir(nonexistent_path):
    print(f"{nonexistent_path} is a directory")
else:
    print(f"{nonexistent_path} is not a directory")

이 수정된 스크립트에서는 세 가지 다른 경로를 확인하고 있습니다.

  • my_directory: 이는 이전 단계에서 생성한 기존 디렉토리입니다.
  • my_file.txt: 이는 이전 단계에서 생성한 기존 파일입니다.
  • nonexistent_path: 이는 존재하지 않는 경로입니다.

check_type.py 파일을 저장합니다.

이제 터미널에서 스크립트를 실행합니다.

python check_type.py

다음과 같은 출력을 볼 수 있습니다.

my_directory is a directory
my_file.txt is not a directory
nonexistent_directory is not a directory

이 출력은 os.path.isdir()my_directory를 디렉토리로 올바르게 식별하고 파일 my_file.txt와 존재하지 않는 경로 nonexistent_directory 모두에 대해 False를 반환함을 보여줍니다. 이는 os.path.isdir()가 경로가 존재하고 디렉토리인 경우에만 True를 반환하기 때문입니다.

이 연습은 경로에 대해 디렉토리별 작업을 시도하기 전에 해당 경로가 디렉토리인지 확인하는 것의 중요성을 강조합니다.

pathlib.Path.is_dir() 로 확인하기

이전 단계에서는 os.path.isdir()를 사용하여 경로가 디렉토리인지 확인했습니다. 이제 파일 시스템 경로에 대한 객체 지향적 접근 방식을 제공하는 pathlib 모듈을 사용하여 동일한 결과를 얻는 또 다른 방법을 살펴보겠습니다.

pathlib 모듈은 파일 시스템 경로를 나타내는 Path 클래스를 제공합니다. 이 클래스에는 경로가 디렉토리인지 확인하는 is_dir() 메서드를 포함하여 파일 및 디렉토리와 상호 작용하기 위한 여러 메서드가 있습니다.

pathlib를 사용하려면 먼저 pathlib 모듈에서 Path 클래스를 가져와야 합니다. 그런 다음 확인하려는 경로를 나타내는 Path 객체를 생성할 수 있습니다. 마지막으로, Path 객체에서 is_dir() 메서드를 호출하여 디렉토리인지 확인할 수 있습니다.

WebIDE 의 코드 편집기에서 check_type.py 파일을 열고 내용을 다음과 같이 수정합니다.

from pathlib import Path

directory_path = Path("my_directory")
file_path = Path("my_file.txt")
nonexistent_path = Path("nonexistent_directory")

if directory_path.is_dir():
    print(f"{directory_path} is a directory")
else:
    print(f"{directory_path} is not a directory")

if file_path.is_dir():
    print(f"{file_path} is a directory")
else:
    print(f"{file_path} is not a directory")

if nonexistent_path.is_dir():
    print(f"{nonexistent_path} is a directory")
else:
    print(f"{nonexistent_path} is not a directory")

이 스크립트에서는 my_directory, my_file.txt, nonexistent_directory에 대한 Path 객체를 생성하고 있습니다. 그런 다음 is_dir() 메서드를 사용하여 각 경로가 디렉토리인지 확인합니다.

check_type.py 파일을 저장합니다.

이제 터미널에서 스크립트를 실행합니다.

python check_type.py

다음과 같은 출력을 볼 수 있습니다.

my_directory is a directory
my_file.txt is not a directory
nonexistent_directory is not a directory

보시다시피, 출력은 os.path.isdir()를 사용했을 때와 이전 단계와 동일합니다. pathlib.Path.is_dir() 메서드는 경로가 디렉토리인지 확인하는 객체 지향적 대안을 제공합니다.

pathlib를 사용하면 특히 복잡한 파일 시스템 작업을 처리할 때 코드를 더 읽기 쉽고 유지 관리하기 쉽게 만들 수 있습니다.

요약

이 Lab 에서는 os.path 모듈을 사용하여 Python 에서 파일과 디렉토리를 구별하는 방법을 배웠습니다. 구체적으로, 디렉토리와 파일을 생성한 다음 os.path.isfile()os.path.isdir()를 사용하여 해당 유형을 확인했습니다. 이 Lab 에서는 이러한 함수를 사용하여 주어진 경로가 파일 또는 디렉토리를 참조하는지 확인하는 방법을 보여주었습니다.