Jeff Triplett

Pathlib Is Wonderful!

Filed under: python

pathlib is a wonderful addition to the Python 3 standard library. The library is an “Object-oriented filesystem paths” module which combines the best of Python’s file system modules like os, os.path, and glob to name a few. This simplifies the number of modules you’ll have to import to work with files and folders.

Here are some highlights that I have noticed in just a few days of playing with the pathlib.

Working with folders

>>> from pathlib import Path

>>> Path('docs').exists()

>>> Path('docs').mkdir()

>>> Path('docs').is_dir()

Listing all of the files in a folder

>>> Path('docs').glob('*.md')
<generator object Path.glob at 0x1128ee258>

# Since generator output isn't obvious :)
>>> [item for item in Path('docs').glob('*.md')]

Working with files

>>> Path('docs', '').is_file()

>>> Path('docs').joinpath('')

Opening a file

>>> Path('').open('r').read()

Writing to a file

>>> Path('').write_text('Read the Docs!')

Reading from file

>>> Path('').read_text()
'Read the Docs!'

What about Python 2?

Even though pathlib is built into Python 3, there is a Python 2.7 backport for anyone who can’t switch yet.

Thank you George Hickman for pointing this out to me on Twitter!