Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Christian Barra
Christian Barra

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
Enter fullscreen modeExit fullscreen mode

We can importPath frompathlib

frompathlibimportPathpath=Path(".")# PosixPath('.')files=[fileforfileinpath.iterdir()]# [PosixPath('subfolder'), PosixPath('README.md'), PosixPath('example.py')]
Enter fullscreen modeExit fullscreen mode

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>
Enter fullscreen modeExit fullscreen mode

Do you want to get only the files with a specific format?

md_files=[fileforfileinpath.iterdir()iffile.suffix=='.md']# [PosixPath('README.md')]
Enter fullscreen modeExit fullscreen mode

You can get a similar result usingglob

md_files=[fileforfileinpath.glob("*.md")]# [PosixPath('README.md')]
Enter fullscreen modeExit fullscreen mode

glob is quite powerful, using the** pattern you can search recursively

md_files=[fileforfileinpath.glob("**/*.md")]# [PosixPath('README.md'), PosixPath('subfolder/README.md')]
Enter fullscreen modeExit fullscreen mode

If you want to learn more about thepathlib module thePEP 428 and theofficial documentation are the right places where to start.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Code writer • Founder of Machinalia • Teaching everything I know at @pybootcamp • @ThePSF Fellow
  • Joined

More fromChristian Barra

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp