# Idea
```python
from pathlib import Path
Path.cwd()
Path.home()
# forward slash to jion paths independent of platform
Path.home() / 'dropbox' / 'myfolder'
Path.home().joinpath('dropbox', 'myfolder') # same as above
# construct file path
p = Path.cwd()
p / 'results' / 'archive'
p.joinpath('results', 'archive')
p.joinpath(*['a', 'b']) # unpack
# get directory listing
p.iterdir()
# get full path
p.resolve()
# attributes of path
p = p / 'scratch'
p.name # final path component
p.parent # returns new object
list(p.parents) # all parents
p.stem # file name without suffix
p.suffix # extension
list(p.suffixes)
p.anchor # the part of the path before the directories
p.parts # parts of the path
# methods
p.exists()
p.with_name() # rename file
p.is_dir()
p.is_file()
p.mkdir(parents=False, exists_ok=False)
p.as_uri()
p.replace()
p.rmdir()
p.stat() # info about path (like os.stat())
# list all subdirectories
p = Path.cwd()
list(p.iterdir())
# list matching files with glob
list(p.glob("*.py"))
# list everything in a directory
list(p.parent.glob("*"))
# remove file or symbolic link
p.unlink(missing_ok=False) # parameter added in python3.8
```
![[Pasted image 20210609213623.png|800]]
From https://github.com/chris1610/pbpython/blob/master/extras/Pathlib-Cheatsheet.pdf
![[Pasted image 20210609212645.png|1000]]
![[Pasted image 20210609212710.png|1000]]
# References
- [pathlib — Object-oriented filesystem paths — Python 3.11.0 documentation](https://docs.python.org/3/library/pathlib.html)
- [Python 3's pathlib Module: Taming the File System – Real Python](https://realpython.com/python-pathlib/)
- [Using Python's pathlib Module – Real Python](https://realpython.com/courses/pathlib-python/)
- [Practical Recipes for Working With Files in Python – Real Python](https://realpython.com/courses/practical-recipes-files/)
- [Using Python’s Pathlib Module - Practical Business Python](https://pbpython.com/pathlib-intro.html)