File path

2 snippets in Python

PYPython

pathlib (Modern Path Handling)

PY · File I/O
syntax
from pathlib import Path
example
from pathlib import Path

data_dir = Path("project") / "data"
data_dir.mkdir(parents=True, exist_ok=True)

config = data_dir / "settings.json"
config.write_text('{"debug": true}', encoding="utf-8")
print(config.read_text())
print(config.suffix, config.stem)
output
{"debug": true}
.json settings

Note pathlib is the modern replacement for os.path. The / operator joins paths. Use .resolve() for absolute paths, .exists() to check existence.

os and os.path

PY · Common Standard Library
syntax
import os
os.path.join()
os.environ
example
import os

# Environment variables
db_host = os.environ.get("DB_HOST", "localhost")
print(f"DB: {db_host}")

# Path operations (prefer pathlib for new code)
print(os.path.expanduser("~"))
print(os.path.splitext("report.pdf"))
print(os.getcwd())
output
DB: localhost
/Users/username
('report', '.pdf')
/current/directory

Note Prefer pathlib.Path for path manipulation in new code. os.environ provides direct access to environment variables. Use os.getenv() for safe access with defaults.