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()
False

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

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

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')]
[PosixPath('docs/README.md')]

Working with files

>>> Path('docs', 'README.md').is_file()
True

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

Opening a file

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

Writing to a file

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

Reading from file

>>> Path('README.md').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!