Using Pathlib
Basics
Section titled “Basics”from pathlib import Path
current = Path('.')my_file = Path('/home/user/docs/file.txt')absolute = Path(__file__).resolve()
Filesystem navigation
Section titled “Filesystem navigation”from pathlib import Path
# Go up one or more directoriesparent = Path(__file__).resolve().parentgrandparent = Path(__file__).resolve().parents[1]# Move into a subdirectorysubdir = parent / "my_folder"
Check path properties
Section titled “Check path properties”p = Path("example.txt")
p.exists() # Check if path existsp.is_file() # Is it a file?p.is_dir() # Is it a directory?
# Read and write filesfile = Path("example.txt")
file.write_text("Hello, pathlib!")content = file.read_text()print(content)
# iterate over a dirfor path in Path('.').iterdir(): print(path)
# globbingfor py_file in Path('.').rglob('*.py'): print(py_file)