Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 48 of 70

Python pathlib: working with file paths

Build and inspect file paths with pathlib.Path, create folders, read and write text, list and search files, and write code that works on any operating system.

13 minErrors and filesUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonBuild paths with the / operator, read their parts, create folders, list and search files, and read and write small files with Path methods.

After this lesson you will be able to build file and folder paths safely, ask questions about them, create folders and find files, without worrying about whether you are on Windows, macOS or Linux. The tool for this is pathlib, part of Python's standard library.

From strings to Path objects

You could write paths as plain strings such as "reports/2026/sales.csv", but then separators differ between systems and every task needs string slicing. pathlib.Path represents a path as an object with useful behaviour.

python
from pathlib import Path

folder = Path("reports")
file = folder / "2026" / "sales.csv"

print(file)
print(isinstance(file, Path))
result
reports/2026/sales.csv
True

The / operator joins parts. The result is printed with the separator your system uses. On Windows you would see backslashes instead of the forward slashes shown here, and the same code runs unchanged.

The parts of a path

A path knows its own pieces, so there is no need for string slicing.

python
p = Path("reports/2026/sales.csv")

print(p.name)
print(p.stem)
print(p.suffix)
print(p.parent)
print(p.parts)
print(p.with_suffix(".json"))
print(p.with_name("totals.csv"))
result
sales.csv
sales
.csv
reports/2026
('reports', '2026', 'sales.csv')
reports/2026/sales.json
reports/2026/totals.csv

name is the last piece, stem is the name without its extension, and suffix is the extension including the dot. The with_suffix and with_name methods return new paths and change nothing on disk. Paths are never modified in place.

Checking what exists

Making a path object does not touch the disk. Ask questions when you need to know.

python
p = Path("reports/2026/sales.csv")
print(p.exists())
print(Path(".").is_dir())
result
False
True

Creating folders

mkdir creates a folder. parents=True also creates any missing folders above it, and exist_ok=True stops it complaining if the folder is already there. Together they make a safe "make sure this folder exists" call.

python
p.parent.mkdir(parents=True, exist_ok=True)
print(p.parent.is_dir())
result
True

Reading and writing small files

For small text files, write_text and read_text do the opening, the closing and the work in a single call.

python
p.write_text("region,total\nNorth,120\nSouth,95\n", encoding="utf-8")

print(p.exists())
print(p.is_file())
print(p.read_text(encoding="utf-8"))
result
True
True
region,total
North,120
South,95

These methods are perfect for small files. For large files, or when you want to loop over lines, use p.open() inside a with block, which works just like the built-in open().

python
with p.open(encoding="utf-8") as f:
    for line in f:
        print(line.strip().upper())
result
REGION,TOTAL
NORTH,120
SOUTH,95

Listing and searching folders

iterdir() gives everything directly inside a folder, in no guaranteed order, so sort when the order matters. glob() finds paths matching a pattern, where * means any text, and rglob() searches all the subfolders as well.

python
(Path("reports") / "2026" / "notes.txt").write_text("remember to check totals\n", encoding="utf-8")
(Path("reports") / "summary.txt").write_text("year summary\n", encoding="utf-8")

for item in sorted(Path("reports").iterdir()):
    print(item, "folder" if item.is_dir() else "file")

print([str(x) for x in sorted(Path("reports").glob("*.txt"))])
print([str(x) for x in sorted(Path("reports").rglob("*.txt"))])
result
reports/2026 folder
reports/summary.txt file
['reports/summary.txt']
['reports/2026/notes.txt', 'reports/summary.txt']

The first glob only looked inside reports, so it found one file. The rglob looked inside reports/2026 as well, so it found two.

Renaming and deleting

rename moves or renames a path and unlink deletes a file. Be careful, because deleted files do not go to a recycle bin.

python
summary = Path("reports") / "summary.txt"
renamed = summary.rename(Path("reports") / "year-summary.txt")

print(renamed)
print(summary.exists())

renamed.unlink()
print(renamed.exists())
result
reports/year-summary.txt
False
False

Building paths that do not depend on the folder you run from

A relative path depends on where the program was started, which was the problem raised in the reading-files lesson. In a saved script, a reliable trick is to anchor paths to the script's own location. The special name __file__ holds the script's path, but it exists only when running a script file, so this example is not run here.

python
from pathlib import Path

BASE = Path(__file__).resolve().parent
data_file = BASE / "data" / "loans.csv"

Path.home() gives the current user's home folder and Path.cwd() the current working directory. Both are useful, but their results differ for every computer.

Common mistakes

  • Joining with +. Path("a") + "b" raises a TypeError. Use the / operator.
  • Expecting iterdir() to be sorted. Wrap it in sorted() when the order matters.
  • Calling mkdir() twice. The second call fails with FileExistsError unless you pass exist_ok=True.
  • Hard-coding backslashes. "data\\file.txt" works only on Windows. Use Path("data") / "file.txt".
  • Forgetting that a Path is not a string. Many functions accept paths, but if one wants a string, wrap the path in str().

Exercise

Create a folder library/books, write a file dune.txt inside it with the text Frank Herbert, then print the file's name, its suffix and its contents. Finally, print a sorted list of every .txt file under library.

Show one possible answer
python
from pathlib import Path

books = Path("library") / "books"
books.mkdir(parents=True, exist_ok=True)

book = books / "dune.txt"
book.write_text("Frank Herbert", encoding="utf-8")

print(book.name)
print(book.suffix)
print(book.read_text(encoding="utf-8"))
print([str(x) for x in sorted(Path("library").rglob("*.txt"))])
result
dune.txt
.txt
Frank Herbert
['library/books/dune.txt']

Next comes the modules section, starting with how to import code from other files. A video version of this topic is in the video course at /learn/python/.

Key points

  • pathlib.Path treats a path as an object, and the / operator joins parts so you do not glue strings together.
  • A path has parts you can read: name, stem, suffix, parent and parts.
  • exists(), is_file() and is_dir() check what is there, and mkdir(parents=True, exist_ok=True) creates folders safely.
  • read_text() and write_text() handle small files in one call, and iterdir() and glob() list and search folders.
  • The same code works on Windows, macOS and Linux, because Path uses the right separator for each.

Check yourself

1. What does Path('reports') / 'sales.txt' produce?
2. What is the suffix of Path('data/loans.csv')?
3. Which call creates nested folders and does not fail if they already exist?
4. Why is pathlib better than joining paths with + and slashes?