How do I work with file paths and directories in Python?

· Category: Python Programming

Short answer

Use pathlib.Path for modern, object-oriented path manipulation. For older code, os.path is still available. Both allow you to join paths, check existence, list directories, and create folders portably.

Steps

  1. Create a Path object: from pathlib import Path.
  2. Use / to join paths.
  3. Use methods like .exists(), .mkdir(), .glob(), and .read_text().
from pathlib import Path

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

file_path = data_dir / "input.txt"
if file_path.exists():
    print(file_path.read_text(encoding="utf-8"))

# List files
for txt_file in data_dir.glob("*.txt"):
    print(txt_file.name)

Tips

  • pathlib is preferred over os.path for new code because it is more readable and cross-platform.
  • Use Path.home() and Path.cwd() to get the home directory and current working directory.
  • os.walk() is still useful for recursive directory traversal with complex filtering.
# os.walk example
import os
for root, dirs, files in os.walk("."):
    for name in files:
        print(os.path.join(root, name))

Common issues

  • Hardcoding backslashes (\) breaks on Linux/macOS; always use pathlib or os.path.join.
  • mkdir() without exist_ok=True raises FileExistsError if the directory already exists.
  • Relative paths depend on the current working directory, which may differ between IDE, terminal, and cron jobs.