Python Tutorial / Manage File and Folder Paths with pathlib

pathlib.Path represents file-system paths and joins them using the operating system’s path rules. Relative paths are resolved from the current working directory, which may differ from the folder containing your script.

Use path operations instead of manual separators

Path("data") / "expenses.csv" joins path components without manually inserting Windows backslashes or platform-specific separators. Constructing a Path does not create a file.

Path.cwd() reports the working directory. In a script, Path(__file__).resolve().parent can identify its containing folder, but __file__ may be unavailable in an interactive environment. Choose the base directory as part of the program’s interface rather than assuming these locations are identical.

For the relevant APIs and platform requirements, see Manage File and Folder Paths with pathlib documentation.

Create and inspect a practice file

Use a fresh practice folder: this example writes lab-data/expenses.csv and replaces its contents if it already exists.

Save the complete code below as paths.py in a separate practice folder, using UTF-8. Run python paths.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

from pathlib import Path

base = Path("lab-data")
base.mkdir(exist_ok=True)
path = base / "expenses.csv"
path.write_text("name,amount\nlunch,8000\n", encoding="utf-8")
print(path.name, path.suffix, path.stem)
print(path.is_file(), base.is_dir())
print(sorted(p.name for p in base.glob("*.csv")))

Expected output:

expenses.csv .csv expenses
True True
['expenses.csv']

Understand searches and existence checks

glob("*.csv") searches the specified folder; rglob("*.csv") includes subfolders. Filter with is_file() when only files are acceptable, and sort results when stable display order matters.

A path can change between an exists() check and the actual operation. Existence checks help provide an explanation but cannot eliminate permission failures, concurrent changes or disk errors. Important writes still need exception handling and an explicit overwrite policy.

Compare execution locations and contain external paths

Running the script from another working directory creates another lab-data beneath that directory. Whether this is correct depends on the documented path contract. Open the generated CSV and verify its header and expense row before cleanup.

  1. Change the filename and compare name, stem and suffix.
  2. Run from a different folder and identify the actual output location.
  3. Resolve the absolute path before deleting only the disposable files created by this exercise.

For externally supplied paths, consider parent traversal, absolute paths and symbolic links. A string-prefix comparison is insufficient to establish that the resolved target lies inside an allowed directory. The batch file operations lesson applies scope checks before file changes.