[Python] pathlib

2021. 3. 24. 15:29Python

728x90

(pathlib는 python3.4부터 built-in module에 포함되었다)

 

pathlib : Object-oriented filesystem paths

파일 시스템 경로를 단순한 문자열(str)로 다루는 것이 아닌, 객체로 다룬다.

이 점이 os.path 모듈과(pathlib는 python3.4부터 built-in module에 포함되었다)

 

pathlib : Object-oriented filesystem paths

파일 시스템 경로를 단순한 문자열(str)로 다루는 것이 아닌, 객체로 다룬다.

 

이 점이 os.path 모듈과는 다른 점이다.

Path 객체의 상속 구조

일반적인 용도의 경로를 다룰 때는 그냥 Path를 사용하면 되지만, 다른 os의 path를 다룰 떄에는 PurePath를 사용해야한다.


Usage

- 파일 열기

path = Path(filename)

file = path.open('r')

path = Path(filename)
file = path.open('r')

 

- 파일 읽고 쓰기 - 한번의 I/O만 필요할 때

  • Path.write_text()
  • Path.write_bytes()
  • Path.read_text()
  • Path.read_bytes()
path = Path(filename)
r = path.read_text()

- 경로 분석

from pathlib import Path

path = Path('/usr/bin/python3')

path
# PosixPath('/usr/bin/python3')

str(path)
# '/usr/bin/python3'

path.parts
# ('/', 'usr', 'bin', 'python3')

path.parent
# PosixPath('/usr/bin')

list(path.parents)
# [PosixPath('/usr/bin'), PosixPath('/usr'), PosixPath('/')]

# -----

path = Path('/usr/bin/python3/../')

# 주의!
path.parent
# PosixPath('/usr/bin/python3')

path.resolve()
# PosixPath('/usr/bin')

- file/directory listing (glob pattern 사용)

from pathlib import Path

path = Path('.')

files = path.glob('*')
# <generator object Path.glob at 0x7f0ff370a360>

list(files)
# [PosixPath('.git'), PosixPath('.gitconfig'), PosixPath('.vimrc'), PosixPath('.zshrc'), PosixPath('pre-commit')]

# path.rglob(*)도 동일하다
list(path.glob('**/*'))
# [PosixPath('.git/COMMIT_EDITMSG'), PosixPath('.git/config'), PosixPath('.git/description'), PosixPath('.git/HEAD'), PosixPath('.git/hooks'), PosixPath('.git/index'), PosixPath('.git/info'), PosixPath('.git/logs'), PosixPath('.git/objects'), PosixPath('.git/refs')]

# path가 가리키는 폴더를 리스팅 할때는 glob('*') 대신 iterdir을 사용할 수 있다.
list(path.iterdir())
# [PosixPath('.git'), PosixPath('.gitconfig'), PosixPath('.vimrc'), PosixPath('.zshrc'), PosixPath('pre-commit')]
728x90

'Python' 카테고리의 다른 글

__getitem__  (0) 2021.05.21
Python argparse  (0) 2021.05.09
2차원 List 뒤집기  (0) 2021.05.01
정규 표현식  (0) 2021.04.29
추상 클래스(abstract class)  (0) 2021.04.08