Module 7 · Beginner · Files and error handling

Python pathlib: work with files and folders

Python pathlib for beginners: build paths that work on every system, read and write files, create folders, find files with glob, rename and delete.

By theprogrammers team · · 9 min read

Your downloads folder has 300 files: invoices, photos, PDFs of notes. You want a script that finds every PDF, makes a folder for each month and moves them in. To do that, the script needs to build file paths, check whether folders exist, list files and move them, and it should work whether your friend runs it on Windows or a Mac. Python pathlib is the modern, built-in way to do all of this.

pathlib treats a path as an object with useful parts and methods, not as a plain string you glue together. Path("data") / "marks.csv" builds a path correctly on every operating system, and path.suffix tells you the file type. This lesson covers the parts of a path, reading and writing files, making folders, finding files, and moving and deleting them safely.

What you need first: Python file handling and Python exceptions.

Key terms

  • Path: the address of a file or folder, like C:\Users\Ahana\notes.txt or /home/ahana/notes.txt.
  • Absolute path: a full address starting from the top of the drive.
  • Relative path: an address starting from the current working directory, the folder your program is running in.
  • Separator: the character between folder names: \ on Windows, / on Mac and Linux.
  • Glob pattern: a simple wildcard pattern for file names, like *.pdf for "every PDF".
  • Path object: pathlib's object that represents a path and has methods to work with it.

Creating a path in Python

from pathlib import Path

report = Path("reports") / "2026" / "december.csv"
print(report.as_posix())
print(type(report).__name__ in ("WindowsPath", "PosixPath"))
reports/2026/december.csv
True

The / operator joins parts of a path, and pathlib puts in the right separator for your system. Printed normally on Windows it shows reports\2026\december.csv; on Mac and Linux it shows reports/2026/december.csv. Here we use .as_posix(), which always uses /, so the output looks the same for everyone.

Compare that with gluing strings together: "reports" + "\\" + "december.csv" only works on Windows, and it's easy to forget a separator or double one up.

Useful starting points:

from pathlib import Path

print(Path.cwd().is_dir())      # the current working directory
print(Path.home().is_dir())     # your user folder, such as C:\Users\Ahana
True
True

We print .is_dir() rather than the paths themselves because your folder names will be different from ours.

The parts of a path

from pathlib import Path

p = Path("projects/college/marks_2026.final.csv")
print(p.name)
print(p.stem)
print(p.suffix)
print(p.suffixes)
print(p.parent.as_posix())
print(p.parent.name)
print(p.parts)
marks_2026.final.csv
marks_2026.final
.csv
['.final', '.csv']
projects/college
college
('projects', 'college', 'marks_2026.final.csv')
AttributeGivesExample result
nameFile name with extensionmarks_2026.final.csv
stemFile name without the last extensionmarks_2026.final
suffixThe last extension, with its dot.csv
parentThe folder that contains itprojects/college
partsEvery piece, as a tuple('projects', 'college', ...)

To get a similar path with one part changed, use with_name, with_stem and with_suffix:

from pathlib import Path

p = Path("data/marks.csv")
print(p.with_suffix(".xlsx").as_posix())
print(p.with_stem("marks_backup").as_posix())
print(p.with_name("notes.txt").as_posix())
data/marks.xlsx
data/marks_backup.csv
data/notes.txt

These only make new Path objects. They don't rename anything on disk.

Checking what exists

from pathlib import Path

p = Path("does_not_exist.txt")
print(p.exists(), p.is_file(), p.is_dir())
False False False

Reading and writing files

For small text files, write_text and read_text open, write or read, and close the file in one call:

from pathlib import Path

notes = Path("notes.txt")
notes.write_text("Revise pathlib\nPractise regex\n", encoding="utf-8")
print(notes.read_text(encoding="utf-8").splitlines())
print(notes.exists())
notes.unlink()          # delete it again
print(notes.exists())
['Revise pathlib', 'Practise regex']
True
False

write_text replaces the whole file. To add lines, or for large files, use open on the path, which works just like the built-in open():

from pathlib import Path

log = Path("visits.txt")
with log.open("a", encoding="utf-8") as f:
    f.write("Ahana\n")
    f.write("Rohan\n")
print(log.read_text(encoding="utf-8").count("\n"), "lines")
log.unlink()
2 lines

Always pass encoding="utf-8"; Unicode and text encodings explains why. For binary files such as images and PDFs, use read_bytes and write_bytes.

Creating folders

from pathlib import Path

folder = Path("demo") / "2026" / "december"
folder.mkdir(parents=True, exist_ok=True)
print(folder.is_dir())
True

The two arguments matter:

  • parents=True creates any missing folders on the way (demo and 2026). Without it, you get FileNotFoundError when a parent folder doesn't exist.
  • exist_ok=True means "don't complain if it's already there". Without it, running the script twice raises FileExistsError.

You'll want both nearly every time.

Listing and finding files

First, make some sample files to search:

from pathlib import Path

base = Path("shop_files")
(base / "invoices").mkdir(parents=True, exist_ok=True)
for name in ["menu.pdf", "logo.png", "prices.csv", "invoices/inv_001.pdf", "invoices/inv_002.pdf"]:
    (base / name).write_text("sample", encoding="utf-8")

print(sorted(p.name for p in base.iterdir()))
print(sorted(p.name for p in base.glob("*.pdf")))
print(sorted(p.as_posix() for p in base.rglob("*.pdf")))
['invoices', 'logo.png', 'menu.pdf', 'prices.csv']
['menu.pdf']
['shop_files/invoices/inv_001.pdf', 'shop_files/invoices/inv_002.pdf', 'shop_files/menu.pdf']
MethodFinds
iterdir()Everything directly inside a folder, files and folders
glob("*.pdf")Matching names directly inside the folder
glob("**/*.pdf") or rglob("*.pdf")Matching names in the folder and every subfolder

In glob patterns, * means "any characters" and ? means "exactly one character": inv_00?.pdf matches inv_001.pdf but not inv_0010.pdf. The order files come back in depends on the system, so sort them when order matters.

To list only files, filter with is_file():

from pathlib import Path

base = Path("shop_files")
files = [p for p in base.iterdir() if p.is_file()]
total = sum(p.stat().st_size for p in files)
print(len(files), "files,", total, "bytes")
3 files, 18 bytes

Each sample file holds the 6-character word "sample", so 3 files take 18 bytes.

Renaming, moving, copying and deleting

from pathlib import Path
import shutil

base = Path("shop_files")

# Rename (or move) a file
new_path = (base / "prices.csv").rename(base / "prices_dec.csv")
print(new_path.name)

# Move every top-level PDF into an archive folder
archive = base / "archive"
archive.mkdir(exist_ok=True)
for pdf in base.glob("*.pdf"):
    pdf.rename(archive / pdf.name)
print(sorted(p.name for p in archive.iterdir()))

# Copy a file (Path.copy only arrived in Python 3.14, so shutil is safer)
shutil.copy(base / "logo.png", base / "logo_copy.png")
print((base / "logo_copy.png").exists())

# Delete a file, then the whole sample folder
(base / "logo_copy.png").unlink()
shutil.rmtree(base)
print(base.exists())
prices_dec.csv
['menu.pdf']
True
False
TaskUse
Rename or move a filepath.rename(new_path)
Copy a fileshutil.copy(src, dst)
Delete a filepath.unlink()
Delete an empty folderpath.rmdir()
Delete a folder and everything in itshutil.rmtree(path)

Be careful with deleting. unlink and rmtree don't use the Recycle Bin or Trash. The file is gone. While testing a script that deletes or moves files, print what it would do first, check the list, and only then run the real thing.

rename raises FileExistsError on Windows if the target already exists, while on Mac and Linux it silently replaces it. Use path.replace(target) when you want to overwrite on every system, or check target.exists() first.

Relative paths and the working directory

A relative path like Path("data.csv") is looked up from the current working directory, not from the folder your script is in. Run the same script from a different folder and it can't find its files. This is the most common "file not found" problem.

To build paths relative to the script itself, use __file__, the path of the current .py file:

from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
data_file = SCRIPT_DIR / "data.csv"
print(data_file.name, data_file.is_absolute())
data.csv True

resolve() turns a path into a full absolute path. (__file__ doesn't exist in Jupyter notebooks; there, paths are relative to the notebook's folder.)

pathlib vs os.path

Older code uses the os and os.path modules for the same jobs. You'll meet them often, so here's how they map:

os / os.pathpathlib
os.path.join("data", "a.csv")Path("data") / "a.csv"
os.path.exists(p)p.exists()
os.path.basename(p)p.name
os.path.splitext(p)[1]p.suffix
os.makedirs(p, exist_ok=True)p.mkdir(parents=True, exist_ok=True)
os.listdir(p)p.iterdir()
os.remove(p)p.unlink()

Use pathlib in new code. It's shorter and harder to get wrong. Most functions that take a file name, including open(), pandas.read_csv() and json.load with open, accept Path objects directly.

Where pathlib is used

  • Automation: sorting downloads, renaming photos, archiving old reports.
  • Data science projects: DATA_DIR = Path(__file__).parent / "data" keeps file paths working on every teammate's laptop.
  • Machine learning: looping over image folders with rglob("*.jpg") to build a training set.
  • Web apps: building paths to upload folders and templates.

Common mistakes

  • Joining paths with + and "\\", which breaks on Mac and Linux. Use / on Path objects.
  • Expecting relative paths to start from the script's folder. They start from the working directory; use Path(__file__).parent.
  • mkdir() without parents=True, exist_ok=True, which fails on the second run.
  • Thinking with_suffix renames a file. It only builds a new path; call rename to change the file.
  • Deleting without a dry run, with nothing to recover from.

Practice

  1. For Path("photos/goa/beach_day1.jpeg"), print the file name, the name without the extension, the extension and the parent folder's name.
Show the answer
from pathlib import Path

p = Path("photos/goa/beach_day1.jpeg")
print(p.name, p.stem, p.suffix, p.parent.name)
beach_day1.jpeg beach_day1 .jpeg goa
  1. Build the path backups/2026/marks.csv from parts, and change its extension to .json.
Show the answer
from pathlib import Path

p = Path("backups") / "2026" / "marks.csv"
print(p.with_suffix(".json").as_posix())
backups/2026/marks.json
  1. Write a script that creates a folder practice, writes three files a.txt, b.txt and c.log into it, prints the names of only the .txt files, and then deletes the folder.
Show the answer
from pathlib import Path
import shutil

folder = Path("practice")
folder.mkdir(exist_ok=True)
for name in ["a.txt", "b.txt", "c.log"]:
    (folder / name).write_text("hi", encoding="utf-8")

print(sorted(p.name for p in folder.glob("*.txt")))
shutil.rmtree(folder)
['a.txt', 'b.txt']
  1. Count how many files of each extension are in a list of paths.
names = ["a.pdf", "b.PDF", "c.jpg", "d.pdf", "e.png", "f.jpg"]
Show the answer

Lower-case the suffix so .PDF and .pdf count together:

from pathlib import Path
from collections import Counter

names = ["a.pdf", "b.PDF", "c.jpg", "d.pdf", "e.png", "f.jpg"]
counts = Counter(Path(n).suffix.lower() for n in names)
print(dict(counts))
{'.pdf': 3, '.jpg': 2, '.png': 1}

On a real folder, replace names with p for p in folder.iterdir() if p.is_file().

  1. A script reads Path("data.csv") and works when you run it from its own folder, but fails with FileNotFoundError when run from elsewhere. Why, and how do you fix it?
Show the answer

Relative paths are resolved from the current working directory, not the script's folder. Build the path from the script's location instead: Path(__file__).resolve().parent / "data.csv".

Interview questions

Why use pathlib instead of os.path?

pathlib represents paths as objects with methods and attributes, uses / to join paths with the right separator for the operating system, and groups most file operations (exists, read, write, glob, mkdir, unlink) in one place. The code is shorter and less error-prone than string-based os.path functions.

What is the difference between glob and rglob?

glob(pattern) matches only within the given directory, unless the pattern contains **. rglob(pattern) searches the directory and all its subdirectories; it's the same as glob("**/" + pattern).

What do parents=True and exist_ok=True do in mkdir?

parents=True creates any missing parent directories. exist_ok=True stops FileExistsError from being raised if the directory already exists.

Key takeaways

  • Path("a") / "b" / "c.csv" builds paths that work on Windows, Mac and Linux.
  • name, stem, suffix and parent give the parts of a path; with_suffix makes a new path.
  • read_text and write_text handle small files in one line; pass encoding="utf-8".
  • mkdir(parents=True, exist_ok=True) creates folders safely; glob and rglob find files.
  • unlink and shutil.rmtree delete permanently, so dry-run first.
  • Relative paths start from the working directory; use Path(__file__).parent for the script's folder.

Frequently asked questions

Is pathlib built into Python?

Yes. It's in the standard library from Python 3.4, so from pathlib import Path works without installing anything.

How do I convert a Path to a string?

str(path) gives the path with your system's separators; path.as_posix() always uses forward slashes. You rarely need either, because most functions accept Path objects directly.

How do I get the size or modified date of a file?

path.stat().st_size gives the size in bytes, and path.stat().st_mtime gives the last-modified time as a timestamp, which datetime.fromtimestamp() turns into a date.

What to learn next

  1. Record what your scripts do in Python logging for beginners.
  2. Revise reading CSV and JSON in Python file handling.
  3. Handle missing files properly with Python exceptions.