romworld

pathlib 본문

Python

pathlib

inderrom 2024. 3. 5. 13:52

python 3.4 버전부터 새로 도입된 파일 경로 및 디렉토리 경로를 다루는 라이브러리.

os.path 모듈보다 객체 지향적이고 간편한 방식으로 경로를 조작할 수 있음.

 

pathlib의 클래스인 Path 클래스는 파일이나 디렉토리의 경로를 나타내기 용이함.

 

from pathlib import Path

 

1. 파일 및 디렉토리 정보 추출


  
file_path = Path("/path/to/file.txt")
print(file_path.name) # 파일명: file.txt
print(file_path.stem) # 파일명 (확장자 제외): file
print(file_path.suffix) # 확장자: .txt
print(file_path.parent) # 부모 디렉토리: /path/to

 

2. 존재 여부 확인


  
existing_file = Path("/path/to/existing_file.txt")
non_existing_file = Path("/path/to/non_existing_file.txt")
print(existing_file.exists()) # True
print(non_existing_file.exists()) # False

 

 

3. 생성 및 삭제


  
new_file = Path("/path/to/new_file.txt")
new_file.touch() # 새로운 파일 생성
existing_file.unlink() # 기존 파일 삭제

 

 

4. 경로 조합


  
path1 = Path("/home/user")
path2 = path1 / "documents" / "file.txt"
Comments