Posted on • Edited on • Originally published atchristianbarra.com
Discovering the pathlib module
ThePython Standard Library is like a gold mine, and thepathlib module is really a gem.
pathlib
provides an useful abstraction on top of different filesystems (posix and Windows).
But that's just a small part of the very friendly user experience that you can have.
# files in my folderREADME.md example.py subfolder/README.md
We can importPath
frompathlib
frompathlibimportPathpath=Path(".")# PosixPath('.')files=[fileforfileinpath.iterdir()]# [PosixPath('subfolder'), PosixPath('README.md'), PosixPath('example.py')]
Path()
returns (in this case) apathlib.PosixPath
object with a very handyiterdir
, a useful generator for when you have a lot of files in your folder.
path.iterdir()<generatorobjectPath.iterdirat0x10aca2cf0>
Do you want to get only the files with a specific format?
md_files=[fileforfileinpath.iterdir()iffile.suffix=='.md']# [PosixPath('README.md')]
You can get a similar result usingglob
md_files=[fileforfileinpath.glob("*.md")]# [PosixPath('README.md')]
glob
is quite powerful, using the**
pattern you can search recursively
md_files=[fileforfileinpath.glob("**/*.md")]# [PosixPath('README.md'), PosixPath('subfolder/README.md')]
If you want to learn more about thepathlib
module thePEP 428 and theofficial documentation are the right places where to start.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse