
Use pathlib.Path instead of os.path for cleaner code.
from pathlib import Path
# Current directory
current = Path(".")
home = Path.home() # /Users/username
# Building paths (works on all OS)
data_dir = Path("data")
file = data_dir / "users" / "alice.json" # uses / operator!
# File info
file.exists() # True/False
file.is_file() # True/False
file.is_dir() # True/False
file.suffix # ".json"
file.stem # "alice"
file.name # "alice.json"
file.parent # data/usersReading/writing:
content = file.read_text() # read as string
bytes = file.read_bytes() # read as bytes
file.write_text("Hello") # write string
file.mkdir(parents=True, exist_ok=True) # create dirsListing files:
for f in Path(".").iterdir():
print(f)
for f in Path(".").glob("*.py"): # pattern matching
print(f)Reference:
TaskLoco™ — The Sticky Note GOAT