Skip to content

Using Pathlib

from pathlib import Path
current = Path('.')
my_file = Path('/home/user/docs/file.txt')
absolute = Path(__file__).resolve()
from pathlib import Path
# Go up one or more directories
parent = Path(__file__).resolve().parent
grandparent = Path(__file__).resolve().parents[1]
# Move into a subdirectory
subdir = parent / "my_folder"
p = Path("example.txt")
p.exists() # Check if path exists
p.is_file() # Is it a file?
p.is_dir() # Is it a directory?
# Read and write files
file = Path("example.txt")
file.write_text("Hello, pathlib!")
content = file.read_text()
print(content)
# iterate over a dir
for path in Path('.').iterdir():
print(path)
# globbing
for py_file in Path('.').rglob('*.py'):
print(py_file)