Skip to content

Path management

Benjamin Loire edited this page Mar 30, 2023 · 1 revision

Use of the pathlib library instead of os.path to manage path.

Pros

  • Less verbose
  • Object-oriented with a set of useful attributes
  • Better readability
  • Works everywhere, compatible with the os module
  • More pythonic

Cons

  • Less used/known

Quickstart

Path("path","to","somewhere") : Create a path object. Without argument, return the current workind directory (analog to os.getcwd())

Path("root").joinpath("subpath","subsubpath") : Extend a path object and return a new path. Analog to os.path.join("root","subpath","subsubpath").

Path("root").glob("*.txt") : Search in the path for files matching the pattern. A better alternative to the glob library. Can also search recursively using rglob().

Path("root","folder").mkdir() : Refer to make_path

Useful attributes

path = Path("root","subpath","file.txt")

print(path.name) #=> file.txt

print(path.stem) #=> file

print(path.suffix) #=> .txt

print(path.parent) #=> Path("root","subpath")

print(path.exists()) #=> True if the path exists

On using os

os.path should be banned, but the os module still has useful functions: os.listdir() vs Path().iterdir() : The former returns the content of a directory as a list whereas the latter returns a generator. A generator yields items one by one and does not have a len() property, but is lighter in memory.

Clone this wiki locally