본문 바로가기
Python

[Python] pathlib.Path 사용하기.

by ds31x 2024. 3. 31.

Path 모듈은

  • file 및 directory의 path 를 객체지향적으로 취급하기 쉬운 인터페이스를 제공하는
  • Python 표준 라이브러리임.

Python 3.4 이상에서 사용가능함.


Path 인스턴스 생성.

from pathlib import Path

# current working directory에 대한 Path인스턴스 생성.
cwd = Path() # Path('.') or Path.cwd()

# 문자열로 path를 지정하여 Path 인스턴스 생성.
path = Path('/home/dsaint31/test.txt')

# 홈디렉토리에 대한 Path 인스턴스 생성.
home_path = Path.home()

 

다음과 같이 상대경로절대경로 를 생성할 수 있음.

from pathlib import Path

path = Path.home() # 사용자의 홈디렉토리에 해당하는 Path인스턴스.

# 상대 경로 생성
relative_path = Path("my_file.txt")

# 절대 경로 생성
absolute_path = path / relative_path # slash연산자를 이용.

# 경로 합치기.
combined_path = Path('/home/dsaint31') / 'my_file1.txt'

주요 속성

  • .name : 해당 경로의 이름. file의 경우 확장자 포함.
  • .stem : 확장자를 제외한 이름. (디렉토리의 경우 .name과 동일)
  • .parent : parent directory.
  • .suffix : file 의 확장자.

주요 메서드

  • .is_file() : file 여부.
  • .is_dir() : directory 여부.
  • .exists() : 존재 여부.

  • .write_text(str_to_write) : 해당 path의 파일에 argument 문자열을 기재.
  • .read_text() : 해당 path의 파일을 읽어서 문자열로 반환.

  • .mkdir() : 해당하는 path의 directory를 생성.
    • parents=True : 관련 경로의 directories 생성.
    • exist_ok=True : 이미 존재하는 경우에도 문제없이 동작.
  • .rmdir() : 해당하는 path의 directory를 삭제.
  • .rename(new_name_fstr) : new_anme_fstr라는 이름으로 file이나 directory의 이름을 변경.

다음은 특정경로에 있는 파일 목록을 순회하는데 사용되는 메서드임.

  • .iterdir() : 해당 path의 모든 파일과 subdirectory를 나열하는 iterator반환.
  • .glob(pattern_str) : 해당 path 에서 pattern_str에 해당하는 파일 목록을 globbing.

아래 예제 참고.

# 현재 디렉터리의 모든 파일과 디렉터리 나열
for child in Path('.').iterdir():
    print(child)

# 특정 패턴과 일치하는 파일 나열
for py_file in Path('.').glob('*.py'):
    print(py_file)

# ** 를 통해 재귀적으로 검색할 수 있음 (하위디렉토리 포함)
for py_file in Path('.').glob('**/*.py'):
    print(py_file)

더 읽어보면 좋은 자료들

https://ds31x.tistory.com/25

 

[Python] os 모듈의 함수들 : file과 directory 관련

os는 operating system (운영체제)와 상호작용을 위한 다양한 기능을 제공하는 built-in module임. 대부분 os 종속적인 기능들이다. os.path 모듈 ds_exist = os.path.exists('path') path가 실제로 존재하는 파일 또는

ds31x.tistory.com

https://realpython.com/python-pathlib/

 

Python's pathlib Module: Taming the File System – Real Python

Python's pathlib module enables you to handle file and folder paths in a modern way. This built-in module provides intuitive semantics that work the same way on different operating systems. In this tutorial, you'll get to know pathlib and explore common ta

realpython.com

 

728x90