728x90
반응형
Path 클래스는 pathlib 모듈의 클래스 :
- 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 의 확장자.
from pathlib import Path
# 파일 경로 예시
p = Path("/home/user/documents/example.txt")
print("전체 경로:", p)
print("파일명(.name):", p.name) # example.txt
print("확장자 제외 이름(.stem):", p.stem) # example
print("부모 디렉토리(.parent):", p.parent) # /home/user/documents
print("확장자(.suffix):", p.suffix) # .txt
# 디렉토리 경로 예시
d = Path("/home/user/documents/folder")
print("\n디렉토리 전체 경로:", d)
print("디렉토리명(.name):", d.name) # folder
print("디렉토리명(.stem):", d.stem) # folder (확장자가 없으므로 .name과 동일)
print("부모 디렉토리(.parent):", d.parent) # /home/user/documents
print("확장자(.suffix):", d.suffix) # '' (빈 문자열)
주요 메서드
.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)
더 읽어보면 좋은 자료들
[Python] os 모듈의 함수들 : file과 directory 관련
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
'Python' 카테고리의 다른 글
| [PyTorch] torch.nn.init (0) | 2024.04.11 |
|---|---|
| [PyTorch] Dataset and DataLoader (0) | 2024.04.09 |
| [DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch) (0) | 2024.03.29 |
| [DL] Define and Run vs. Define by Run (0) | 2024.03.28 |
| [DL] Tensor에서 maximum, minimum 찾기 (0) | 2024.03.28 |