Python
os.path vs pathlib
song
2021. 8. 11. 13:52
os.path cons
- path를 오직 string으로만 관리한다.
- os.path.~ method가 중첩되어 code가 길고 지저분해진다.
별게 없어 보이지만, 모든 면에서 os.path 보다 나쁜 점이 없기에 쓰지 않을 이유가 없다.
pathlib
"pure" keyoword가 붙은 class는 I/O를 포함하지 않는다(OS access 없이 순수하게 path만 조작하고 싶을 때 사용). "posix" or "windows" keyword는 각 os에 맞게 path를 관리하는 class이다. 명시하지 않으면 현재 os에 맞는 객체가 생성된다. (주의, cross os의 normal(non-pure) 객체는 생성이 되지 않는다. pure로 생성해야됨)
usase..
import os
from pathlib import Path
file_path = './path/to/file'
# os.path
if os.path.exists(file_path):
# do something
# pathlib
p = Path(file_path)
if p.exists():
# do something
import os
from pathlib import Path
dir_name = 'dir'
sub_dir_name = 'sub_dir_name'
file_name = 'file'
# os.path
file = os.path.join(dir_name, sub_dir_name, file_name)
# pathlib
dir = Path(dir_name)
file = dir / sub_dir_name / file_name
# os.path
from glob import glob
file_contents = []
for filename in glob('**/*.py', recursive=True):
with open(filename) as python_file:
file_contents.append(python_file.read())
# pathlib
from pathlib import Path
file_contents = [
path.read_text()
for path in Path.cwd().rglob('*.py')
]
# code more explicit
# bad
person = '{"name": "Trey Hunner", "location": "San Diego"}'
pycon_2019 = "2019-05-01"
home_directory = '/home/trey'
# good
from datetime import date
from pathlib import Path
person = {"name": "Trey Hunner", "location": "San Diego"}
pycon_2019 = date(2019, 5, 1)
home_directory = Path('/home/trey')