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.

Frequently asked questions

How does Python handle file path?
Python covers this with 2 copy-ready snippets on this page. The "pathlib (Modern Path Handling)" snippet in Python uses `from pathlib import Path`.
Which code does the Python example use?
The "pathlib (Modern Path Handling)" snippet uses `from pathlib import Path`, from the File I/O section of the Python cheat sheet.
What other Python snippets are shown for "file path"?
Besides "pathlib (Modern Path Handling)", this page also shows "os and os.path".
Is there anything to watch out for?
Yes. For "pathlib (Modern Path Handling)": pathlib is the modern replacement for os.path. The / operator joins paths. Use .resolve() for absolute paths, .exists() to check existence.