Reading history

Python pathlib: Working with Files and Folders

6 min read 1 views

Work with files and folders in Python using pathlib and shutil: build paths, read path parts, create folders, glob and rglob, copy, move and delete safely.

Scripts often need to work with the file system itself: build a path that works on Windows and Linux, check whether a file exists, list every photo in a folder tree, create folders, or move and delete files. Modern Python does this with pathlib, which represents paths as objects with handy methods, plus the shutil module for copying and removing whole folders. This lesson shows the everyday operations in a safe temporary folder.

In this lesson you will learn

  • Building paths with Path and the / operator
  • Reading path parts: name, stem, suffix and parent
  • Creating folders and reading and writing files
  • Finding files with glob, rglob and iterdir
  • Copying, moving and deleting with shutil

You should know file handling and modules.

Paths, Folders and Files

from pathlib import Path
import tempfile

base = Path(tempfile.mkdtemp())          # a fresh, empty folder for the demo
project = base / "project"               # / joins path parts on any OS

# Create folders and files
(project / "data").mkdir(parents=True)
(project / "notes.txt").write_text("Exam on Sunday\n", encoding="utf-8")
(project / "data" / "marks.csv").write_text("name,marks\nNusrat,88\n", encoding="utf-8")
(project / "data" / "old.csv").write_text("x\n", encoding="utf-8")

p = project / "data" / "marks.csv"
print("name:", p.name, "| stem:", p.stem, "| suffix:", p.suffix)
print("parent folder:", p.parent.name, "| exists:", p.exists(), "| is_file:", p.is_file())
print("size:", p.stat().st_size, "bytes")
print("relative:", p.relative_to(base).as_posix())
print("renamed suffix:", p.with_suffix(".txt").name)

print((project / "notes.txt").read_text(encoding="utf-8").strip())

Output

name: marks.csv | stem: marks | suffix: .csv
parent folder: data | exists: True | is_file: True
size: 21 bytes
relative: project/data/marks.csv
renamed suffix: marks.txt
Exam on Sunday
  • tempfile.mkdtemp() creates a new empty folder, so the example cannot touch your real files.
  • base / "project" joins path parts with the correct separator for the operating system (\ on Windows, / elsewhere). Never build paths by gluing strings together.
  • mkdir(parents=True) creates any missing parent folders too. Add exist_ok=True to avoid an error if the folder already exists.
  • write_text and read_text open, write or read, and close a file in one call. Use them for small files; use open() for large files or line-by-line work.
  • name, stem, suffix and parent split a path into parts without any string slicing. with_suffix returns a new path with a different extension.
  • exists(), is_file() and stat().st_size answer questions about the file on disk.
from pathlib import Path
import shutil
import tempfile

root = Path(tempfile.mkdtemp())
for name in ["a.csv", "b.csv", "report.pdf", "photos/x.jpg", "photos/2026/y.jpg"]:
    f = root / name
    f.parent.mkdir(parents=True, exist_ok=True)
    f.write_text("demo", encoding="utf-8")

# glob: files in one folder; rglob: search every subfolder
print(sorted(p.name for p in root.glob("*.csv")))
print(sorted(p.relative_to(root).as_posix() for p in root.rglob("*.jpg")))

# iterdir lists a folder's direct children
for child in sorted(root.iterdir()):
    print(("DIR " if child.is_dir() else "FILE"), child.name)

# Move, copy and delete
backup = root / "backup"
backup.mkdir()
shutil.copy(root / "a.csv", backup / "a.csv")
(root / "b.csv").rename(backup / "b.csv")
(root / "report.pdf").unlink()
shutil.rmtree(root / "photos")
print(sorted(p.relative_to(root).as_posix() for p in root.rglob("*")))

# Path.home() and Path.cwd() give the user's home and the current folder
print(Path.home().is_dir(), Path.cwd().is_dir())
shutil.rmtree(root)
print("cleaned up:", not root.exists())

Output

['a.csv', 'b.csv']
['photos/2026/y.jpg', 'photos/x.jpg']
FILE a.csv
FILE b.csv
DIR  photos
FILE report.pdf
['a.csv', 'backup', 'backup/a.csv', 'backup/b.csv']
True True
cleaned up: True
  • glob("*.csv") finds matching files in one folder. rglob("*.jpg") searches every subfolder as well (the r stands for recursive).
  • iterdir() lists a folder’s direct children. The results come in no guaranteed order, so the example sorts them.
  • shutil.copy copies a file, and Path.rename moves or renames one. unlink() deletes a single file.
  • shutil.rmtree deletes a folder and everything inside it, with no recycle bin. Double-check the path before calling it.
  • Path.home() is the user’s home folder and Path.cwd() is the folder the program was started from.

pathlib and os Equivalents

TaskpathlibOlder os / os.path
Join pathsPath("a") / "b"os.path.join("a", "b")
File namep.nameos.path.basename(p)
Folderp.parentos.path.dirname(p)
Exists?p.exists()os.path.exists(p)
Make foldersp.mkdir(parents=True)os.makedirs(p)
List folderp.iterdir()os.listdir(p)
Delete filep.unlink()os.remove(p)
Search treep.rglob("*.py")os.walk(p)

Both styles work and you will see both in existing code. Prefer pathlib in new code; most standard library functions, including open(), accept Path objects.

Common Mistakes

  1. Hard-coding separators, such as "data\\marks.csv", which fails on Linux and macOS.
  2. Assuming the current folder is the script’s folder. Use Path(__file__).parent to find files next to your script.
  3. Calling rmtree on a path built from user input without checking it first.
  4. Checking exists() and then opening, when the file could vanish in between. It is often simpler to try opening and catch FileNotFoundError.

Practice Exercises

Exercise 1. Print the total size, in bytes, of every .py file under the current folder and its subfolders.

Show answer
from pathlib import Path
total = sum(p.stat().st_size for p in Path.cwd().rglob("*.py"))
print(total, "bytes")

Exercise 2. Rename every .txt file in a folder called notes to use the .md extension.

Show answer
from pathlib import Path
for p in Path("notes").glob("*.txt"):
    p.rename(p.with_suffix(".md"))

Frequently Asked Questions

How do I get the folder my script is in?

Use Path(__file__).resolve().parent. It works no matter which folder you run the script from, so files next to the script can be found reliably.

Can I delete a folder that is not empty with pathlib?

Path.rmdir() only removes empty folders. To remove a folder with everything inside it, use shutil.rmtree(path).

Summary

  • Path objects and the / operator build portable paths.
  • name, stem, suffix and parent split paths cleanly.
  • glob and rglob find files; iterdir lists a folder.
  • shutil copies and removes whole folders; use rmtree with care.

Next: Python Mutable vs Immutable and Copying.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *