Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 149 ยท Modules and the Standard Library

Paths with pathlib

Handle files and folders the modern way with pathlib. Build paths with /, inspect names and suffixes, read and write files, create folders and find files with glob.

Programs constantly deal with file locations: where to save a report, which images are in a folder, what a file's extension is. Older Python code juggled these as plain strings with the os.path module. Modern Python uses pathlib, which represents a path as an object with useful properties and methods.

With pathlib, joining paths is as easy as writing /, reading a file is one method call, and the same code works on Windows, macOS and Linux. The editors on this page have an in-memory file system, so every example creates real files you can list, read and delete.

Creating Path objects

Import the Path class and give it a string. Path.cwd() is the current working directory, and Path.home() is the user's home folder:

Python Path basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Path automatically becomes a PosixPath on macOS and Linux (including this browser runner) or a WindowsPath on Windows. You write the same code either way.

Creating a Path doesn't touch the disk. It's just a description of a location; the file may or may not exist.

Joining paths with /

The / operator joins path pieces, inserting the right separator for the operating system. You can mix Path objects and strings:

Python Joining with /

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare that with string concatenation like folder + "/" + name, which breaks on Windows-style separators and doubles slashes when folder already ends with one. Let pathlib handle it.

On Windows, prefer forward slashes or raw strings. Path("C:/Users/kim/Documents") works fine on Windows. If you use backslashes, write a raw string, Path(r"C:\Users\kim\Documents"), so \U and friends aren't treated as escape sequences.

Taking paths apart

A Path exposes every part of itself as a property, which replaces lots of fiddly string slicing:

Python Path parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The with_... methods return a new path; like strings, paths are immutable. They're perfect for deriving output names, such as turning data.csv into data.json.

Absolute paths and files next to your script

A relative path such as Path("data.csv") is resolved against the current working directory, the folder you ran Python from, not the folder your script lives in. Launch the same script from another folder and it suddenly can't find its data. Two tools fix this:

Python
from pathlib import Path

print(Path("data.csv").resolve())        # full absolute path, symlinks resolved
print(Path("~/notes.txt").expanduser())  # ~ becomes your home folder

HERE = Path(__file__).resolve().parent   # the folder containing this script
data_file = HERE / "data" / "prices.csv" # works no matter where you run it from

__file__ is the path of the current module, so Path(__file__).parent is a reliable anchor for files that ship alongside your code. (It isn't defined in the browser editor or the interactive REPL, because there's no script file there.)

Writing and reading files

For small files, write_text() and read_text() do the whole job in one line: open, write or read, and close. write_bytes() and read_bytes() are the binary versions:

Python write_text and read_text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

write_text() replaces any existing content. For appending, streaming large files line by line, or more control, path.open() works exactly like the built-in open(), which the Reading and Writing Files lesson covers in depth.

Pass encoding="utf-8" when reading and writing text. Without it, Python uses the operating system's default encoding, which differs between computers and can garble characters like รฉ or รผ.

Creating, checking and deleting

Python Folders and existence checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • mkdir(parents=True, exist_ok=True) creates every missing folder in the chain and doesn't complain if it already exists. It's the safe default.
  • rename() moves a file and returns the new path; replace() does the same but overwrites an existing target.
  • unlink() deletes a file; rmdir() deletes an empty folder. To delete a folder with contents, use shutil.rmtree(path), carefully.

Listing and finding files

iterdir() lists a folder's direct contents. glob() finds paths matching a wildcard pattern, and rglob() searches all subfolders too:

Python iterdir, glob and rglob

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Glob patterns use * for any characters within one name, ? for a single character, [abc] for one of a set, and ** for "any number of folders". The order of results isn't guaranteed, which is why the example sorts them.

A practical example: organizing files

Here's a small tidy-up script that moves files into folders named after their extension. It combines most of what you've learned:

Python Sort files by type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice list(downloads.iterdir()): the loop moves files while walking the folder, so taking a snapshot first avoids surprises.

A real version of this script would also guard against name clashes: if pdf/invoice.pdf already exists, rename() overwrites it on macOS and Linux but raises FileExistsError on Windows. Checking (destination / item.name).exists() first and choosing a new name, such as adding a number to the stem with with_stem(), makes the script safe to run twice on any system.

pathlib vs os.path

You'll still see os.path in older code and tutorials. Here's how the common calls map:

os / os.path pathlib
os.path.join(a, b) Path(a) / b
os.path.basename(p) p.name
os.path.dirname(p) p.parent
os.path.splitext(p)[1] p.suffix
os.path.exists(p) p.exists()
os.makedirs(p, exist_ok=True) p.mkdir(parents=True, exist_ok=True)
os.listdir(p) p.iterdir()
glob.glob("**/*.py", recursive=True) Path().rglob("*.py")

Most functions that take a file path, including open(), json, csv and shutil, accept Path objects directly. When a library insists on a string, use str(path).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Path("data") / "2026" / "sales.csv" produce on Linux?

    The / operator joins path components and returns a new Path object.
  2. 2. For p = Path("archive.tar.gz"), what is p.stem?

    stem removes only the last suffix. p.suffix is ".gz" and p.suffixes is ['.tar', '.gz'].
  3. 3. Which call creates out/reports/2026 even if out doesn't exist yet, without failing if it already exists?

    parents=True creates missing parent folders and exist_ok=True ignores an existing folder.
  4. 4. What's the difference between glob(\"*.txt\") and rglob(\"*.txt\")?

    glob() matches within the folder itself; rglob() is recursive, like adding **/ to the pattern.

Summary

  • pathlib.Path represents a file system location as an object; creating one doesn't touch the disk.
  • Join paths with /; inspect them with .name, .stem, .suffix, .parent and .parts; derive new ones with with_suffix(), with_name() and with_stem().
  • read_text() / write_text() (with encoding="utf-8") handle small files in one call; path.open() gives full control.
  • mkdir(parents=True, exist_ok=True), exists(), is_file(), rename() and unlink() manage files and folders.
  • iterdir(), glob() and rglob() list and find files.
  • pathlib replaces most of os.path and works the same on every operating system.

Next: Files and Folders with os and shutil.