Your Sunday, upgraded. Free live AI class · 5 PM ISTReserve your seat
PROGRAMMING LANGUAGES

Handle Files and Paths Safely in Python with pathlib

String paths break across operating systems and invite subtle bugs. pathlib gives you path objects with clear methods for joining, reading, writing and checking files.

On this page

The core idea

The pathlib module represents filesystem paths as objects rather than strings. Paths are joined with the / operator, which handles separators correctly on Windows, macOS and Linux. Methods such as read_text, write_text, exists, mkdir and glob replace a mix of functions from os and os.path. Because a Path knows its parts, getting the name, suffix or parent directory is explicit instead of relying on string slicing.

A practical approach

Step 1

Build paths from a known base, such as Path(__file__).parent for files next to your code or a configured data directory, rather than relying on the current working directory.

Step 2

Join with the / operator: base / "reports" / f"{date}.md".

Step 3

Always pass an encoding when reading or writing text, usually encoding="utf-8".

Step 4

Create directories with mkdir(parents=True, exist_ok=True) before writing into them.

Step 5

When a path comes from user input, resolve it and check it stays inside the allowed directory before opening it.

Worked example

A report script works when run from its own folder but fails with FileNotFoundError when scheduled from a different directory, because it opens 'templates/report.md' relative to the working directory. Changing it to Path(__file__).parent / "templates" / "report.md" makes the script work from anywhere, and the same change fixes Windows path separators for a teammate.

A mistake to avoid

Do not build file paths by concatenating user input, for example base + '/' + filename. A value such as '../../etc/passwd' can escape the intended folder. Resolve the final path and confirm it is relative to your base directory.

Try it yourself

Convert one script that uses os.path and string paths to pathlib. Run it from a different working directory and on another operating system if you can, and confirm it still finds its files.

Your implementation checklist

  • Paths are built from a known base directory
  • Paths are joined with Path objects, not strings
  • Text files are read and written with an explicit encoding
  • Output directories are created before writing
  • User-supplied paths are confined to an allowed folder

Share or cite this guide

Innovate with Ajay Editorial (2026-10-07). Handle Files and Paths Safely in Python with pathlib. https://innovatewithajay.com/blogs/handle-files-and-paths-with-pathlib

Editorial approach, sources and corrections

YOUR NEXT CHAPTER

You have the curiosity.
Let’s turn it into capability.

Start with a practical workshop or bring a specific question to Ajay.

Chat with Ajay