-
(Python) os.path vs pathlib.PathIT 지식 창고 2024. 2. 26. 22:25
저는 아래의 이유로 pathlib.Path를 더 선호합니다.
- 가독성 향상
- os에 따른 경로 설정 (windows : WindowsPath, linux : PosixPath를 os에 따라서 알아서 설정하여 각 os별로 처리하는 방법이 다를 때 유용)
- Object Oriented Programming
- Trend (pytorch, yolo 등 활발하게 개발되는 곳에선 Path를 사용)
- etc…
Python으로 개발 시, os.path를 활용하여 경로를 주로 다룰 수 있으나, python 3.4부터 pathlib이라는 경로 관련 객체 지향 python library가 추가되었습니다.
예제
os.path와는 어떻게 다른지 제가 자주사용하는 기능 위주로 정리해보고자 합니다.
python pathlib official documentation : https://docs.python.org/ko/3/library/pathlib.html
pathlib — Object-oriented filesystem paths
Source code: Lib/pathlib.py This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which p...
docs.python.org
Setup
import os from pathlib import Path # 주로, 다음과 같이 import 하여 Path 객체를 활용함.
현재 경로
# os print(os.getcwd()) # pathlib print(Path.cwd()) # print(Path().resolve())
absolute
# os PATH = "./" p = os.path.abspath(PATH) print(p) # pathlib PATH = "./" p = Path(PATH).resolve() print(p)
join
# os PATH = "./os" p = os.path.abspath(PATH) p = os.path.join(p, "test1") p = os.path.join(p, "test2") p = os.path.join(p, "test3") p = os.path.join(p, "os.txt") print(p) # os.path.join(p, "test1", "test2", "test3" "os.txt") # pathlib PATH = "./pl" p = Path(PATH).resolve() # pl이라는 폴더가 없어서 상대경로로 나옴. p = p / "test1" p = p / "test2" p = p / "test3" p = p / "pl.txt" print(p) # p / "test1" / "test2" / "test3" / "pl.txt")
file 및 directory 생성
dir
# os PATH = "./" p = os.path.join(PATH, "os", "test1", "test2", "test3") os.makedirs(p, exist_ok=True) print(p) # pathlib PATH = "./" p = Path(PATH) / "pl" / "test1" / "test2" / "test3" p.mkdir(parents=True, exist_ok=True) print(p)
file
# os PATH = "./" p = os.path.join(PATH, "os", "test1", "test2", "test3") f = open(os.path.join(p, 'os.txt'), 'w') f.close() # pathlib PATH = "./" p = Path(PATH) / "pl" / "test1" / "test2" / "test3" (p / "pl.txt").write_text("")
exist (all, file, dir)
all
# os PATH = "./" p = os.path.abspath(PATH) print(os.path.exists(p)) # pathlib PATH = "./" p = Path(PATH).resolve() print(p.exists())
file
# os PATH = "./" p = os.path.abspath(PATH) print(os.path.isfile(p)) # pathlib PATH = "./" p = Path(PATH).resolve() print(p.is_file())
dir
# os PATH = "./" p = os.path.abspath(PATH) print(os.path.isdir(p)) # pathlib PATH = "./" p = Path(PATH).resolve() print(p.is_dir())
특정 경로의 file 및 directory 나열
file 및 directory 명만 나열
# os PATH = "./" p = os.path.abspath(PATH) os.listdir(p) # pathlib PATH = "./" p = Path(PATH).resolve() [x.name] for x in p.iterdir()] # [x.name for x in list(p.glob("*"))]
경로도 포함하여 나열
# os PATH = "./" p = os.path.abspath(PATH) [os.path.abspath(x) for x in os.listdir(p)] # pathlib PATH = "./" p = Path(PATH).resolve() [str(x) for x in p.iterdir()] # list(p.iterdir()) or list(p.glob("*"))
특정 file만 나열
# os PATH = "./" p = os.path.join(PATH, "os", "test1", "test2", "test3") [x for x in os.listdir(p) if x.endswith(".txt")] # glob library를 활용할 수도 있음. # pathlib # pathlib은 pattern으로 다양하게 활용 가능. PATH = "./" p = Path(PATH) / "pl" / "test1" / "test2" / "test3" [x.name for x in p.glob("*.txt")]
기타
경로 중 file 명 및 확장자 출력
# 확장자 포함 PATH = "./root.txt" p = Path(PATH) p.name
# 확장자 제외 # 단, .nii.gz일 경우는 stem 사용 x (.gz만 제외됨) PATH = "./root.txt" p = Path(PATH) p.stem
# 확장자만 PATH = "./root.txt" p = Path(PATH) print(p.suffix) # .으로 다 분리 PATH = "./1.23.3.root.nii.gz" p = Path(PATH) print(p.suffixes)
상위 경로
PATH = "./" p = Path(PATH).resolve() print(p) print(p.parent) # 모든 상위 경로 PATH = "./" p = Path(PATH).resolve() print(p) list(p.parents)
remove
# 하위 목록까지 모두 삭제는 shutil을 활용하는 게 좋음. import shutil shutil.rmtree("os") shutil.rmtree("pl")
'IT 지식 창고' 카테고리의 다른 글
(torchio) 3D Data Augmentation 중 주로 사용하는 기법 (0) 2024.05.14 (Git) 이전 Commit에서 특정 file만 삭제하기 (filter-repo) (1) 2024.03.22 (Python) 간단한 커스텀 프로그레스 바 코드 (0) 2024.02.21 (Pytorch) Pytorch에서 학습 및 테스트 시 GPU VRAM이 계속 증가하는 이유 (2) 2024.02.14 (Docker) docker container 내에서 root계정과 root권한을 가진 사용자 계정 사용하기 (0) 2023.08.03 댓글