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
Pathand the/operator - Reading path parts: name, stem, suffix and parent
- Creating folders and reading and writing files
- Finding files with
glob,rglobanditerdir - 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. Addexist_ok=Trueto avoid an error if the folder already exists.write_textandread_textopen, write or read, and close a file in one call. Use them for small files; useopen()for large files or line-by-line work.name,stem,suffixandparentsplit a path into parts without any string slicing.with_suffixreturns a new path with a different extension.exists(),is_file()andstat().st_sizeanswer questions about the file on disk.
Searching, Moving and Deleting
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.copycopies a file, andPath.renamemoves or renames one.unlink()deletes a single file.shutil.rmtreedeletes 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 andPath.cwd()is the folder the program was started from.
pathlib and os Equivalents
| Task | pathlib | Older os / os.path |
|---|---|---|
| Join paths | Path("a") / "b" | os.path.join("a", "b") |
| File name | p.name | os.path.basename(p) |
| Folder | p.parent | os.path.dirname(p) |
| Exists? | p.exists() | os.path.exists(p) |
| Make folders | p.mkdir(parents=True) | os.makedirs(p) |
| List folder | p.iterdir() | os.listdir(p) |
| Delete file | p.unlink() | os.remove(p) |
| Search tree | p.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
- Hard-coding separators, such as
"data\\marks.csv", which fails on Linux and macOS. - Assuming the current folder is the script’s folder. Use
Path(__file__).parentto find files next to your script. - Calling
rmtreeon a path built from user input without checking it first. - Checking
exists()and then opening, when the file could vanish in between. It is often simpler to try opening and catchFileNotFoundError.
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
Pathobjects and the/operator build portable paths.name,stem,suffixandparentsplit paths cleanly.globandrglobfind files;iterdirlists a folder.shutilcopies and removes whole folders; usermtreewith care.
