Created
March 4, 2026 12:14
-
-
Save docPhil99/00eda42df8950fb356af840b509cf40c to your computer and use it in GitHub Desktop.
Python Pathlib cheat sheet demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pathlib import Path | |
| p = Path("/home/user") / "projects" / "demo.jpg" | |
| print(p.name) #demo.jpg | |
| print(p.parent) # /home/user/projects | |
| print(p.suffix) # .jpg | |
| print(p.stem) # demo | |
| print(list(p.parents)) #[PosixPath('/home/user/projects'), PosixPath('/home/user'), PosixPath('/home'), PosixPath('/')] | |
| print(p.is_file()) # True if file exists | |
| print(p.is_dir()) # false in this case | |
| print(p.with_suffix('.png')) # /home/user/projects/demo.png | |
| for sp in p.iterdir(): #iterate over all subdirectories and files | |
| print(sp) #test with is_file or is_dir to get the type | |
| [x for x in p.iterdir() if x.is_dir()] # list of subdirectories | |
| for sp in Path.cwd().glob('*.py') # find all *.py files in current working directory | |
| print(sp) | |
| #glob('**/*.py') makes this recursive, same as rglob() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment