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