Idiomatic Python 2/3 compatible pathlib use

pathlib is an object-oriented, Python standard way to handle paths and filenames instead of manipulating strings. With pathlib.Path(), very obtuse and cumbersome code can be condensed to a single readable line–you may never need os.path again.

pathlib is standard and supported throughout Python 3.6 natively, as well as in the SciPy stack and elsewhere.

Python 2/3 pathlib compatibility

Python standard library pathlib can be used for Python 2.6, 2.7 and newer via

pip install pathlib2

You can thus use pathlib correctly from Python 2.6 on up by putting in your

    from pathlib import Path
except (ImportError,AttributeError):
    from pathlib2 import Path

and then in your package .py files

from . import Path

pathlib glob like GNU find

pathlib.Path.glob() recursively searches for files.

allpy = Path('~').expanduser().glob('*.py')

returns a generator that you can iterate over with a for loop, or enclose in sorted() to get a list.



Leave a Comment