Skip to Content

Path Objects

Python 3.4 added path objects, but most people still don’t know about them. They simplify a lot of file operations:

### Without pathlib

path = "path/to/file"

# parent dir
os.path.dirname(path)

# file suffix
os.path.splitext(path)[1]

# read file
with open(path) as f:
  x = f.read()


### With pathlib

path = pathlib.Path("path/to/file")

# parent dir
path.parent

# file suffix
path.suffix

# read file
x = path.read_text()

Paths are also OS-independent, so the same code will generally work on both Windows and Unix.