Pathlib

Easy path handling in Python

Use library pathlib to handle paths in Python (starting from Python 3.4):

from pathlib import Path

p = Path('/etc')

Basics

  • Use operator / to navigate in the tree: q = p / 'init.d' / 'reboot'
  • Iterating : p.iterdir()
  • Querying : p.exists(), p.is_dir()
  • Opening a file: with q.open() as f: f.readline()
  • Get filename: p.name
  • Get suffix: p.suffix
  • Create directory(ies): p.mkdir()
  • Can be converted into string !

Documentation

https://docs.python.org/3/library/pathlib.html