python pkgs) pathlib 알아보기
2021. 9. 22. 20:07ㆍ분석 Python/Packages
목차
Working Directory
Get a path to the current Python file
curr_file = pathlib.Path(__file__)
print(curr_file)
Get a path to the current working directory
cwd = pathlib.Path.cwd()
print(cwd)
Get a first parent folder path
parent folder 찾기
one_above = pathlib.Path.cwd().parent
print(one_above)
Get an Nth parent folder path
N번째 상위 폴더를 찾는 방법
mul_above = pathlib.Path.cwd().parent.parent.parent
mul_above = pathlib.Path.cwd().parents[1]
print(mul_above)
Join paths
Create a directory if it doesn’t exist
tgt_path = pathlib.Path.cwd().joinpath('reports')
if not tgt_path.exists():
tgt_path.mkdir()
Create files
reports라는 폴더에 파일 생성하기
tgt_path = pathlib.Path.cwd().joinpath('reports')
tgt_path.joinpath('summer-sales.csv').touch(exist_ok=True)
tgt_path.joinpath('winter-sales.txt').touch(exist_ok=True)
Check if the path is a folder
폴더가 있는 지 여부 확인
tgt_path = pathlib.Path.cwd().joinpath('reports')
print(tgt_path.is_dir())
print(tgt_path.joinpath('summer-sales.csv').is_dir())
Check if the path is a file
tgt_path = pathlib.Path.cwd().joinpath('reports')
print(tgt_path.is_dir())
print(tgt_path.joinpath('summer-sales.csv').is_file())
Get the name of the file
tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')
print(tgt_path.name)
Get the file extension
tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')
print(tgt_path.suffix)
#.csv
Iterate over files in a folder
tgt_path = pathlib.Path.cwd().joinpath('reports')
for file in tgt_path.iterdir():
print(file)
https://pbpython.com/pathlib-intro.html
728x90
'분석 Python > Packages' 카테고리의 다른 글
Python) pregex 로 편하게 정규 표현식 사용하기 (0) | 2022.07.30 |
---|---|
Python) pipreqs - 특정 폴더안에 있는 파이썬 패키지를 requirements.txt 만들어주는 패키지 (0) | 2021.10.13 |
python3) KeyError : 'PROJ_LIB' 문제 해결하기 (Basemap) (0) | 2021.06.29 |
python3) basemap install in ubuntu 18.04 (0) | 2021.06.29 |
Python Pkg) array를 gif로 바꿔주는 패키지 (0) | 2021.05.13 |