Python 3D Academyবাংলা

Paths and folders: pathlib

🌍 In real life. A letter's address goes from big to small: country, city, road, house. A file's address works the same way: a folder, folders inside it, and finally the file. That address is called a path, like notes/day1.txt.

The idea in one sentence: pathlib.Path turns a path into an object you can join with /, take apart (name, extension, folder), check, read, write, and use to list a folder.

Its words:

  • path: a file's or folder's address; notes/day1.txt is relative, starting from the folder the program runs in
  • folder (directory): a box that holds files and other folders
  • name, stem, suffix, parent: for notes/day1.txt: day1.txt, day1, .txt, and notes
  • glob: a pattern for many files at once: *.txt means every name ending in .txt

Step by step:

  1. from pathlib import Path, then folder = Path("notes")
  2. folder / "day1.txt" joins the parts with the right separator for the computer
  3. .exists() asks whether something is there; .read_text() and .write_text(text) read or write the whole file in one call
  4. folder.glob("*.txt") gives every matching path in the folder
from pathlib import Path

folder = Path("notes")
p = folder / "day1.txt"
print(p, "|", p.name, p.stem, p.suffix, p.parent)
print(p.exists(), (folder / "day9.txt").exists())
print(p.read_text().splitlines())

for f in sorted(folder.glob("*.txt")):
    print(f.name, "has", len(f.read_text().splitlines()), "lines")

Why / and not +. Windows writes paths with a backslash (notes\day1.txt) and macOS and Linux with a slash. Gluing strings with + "/" bakes one of them in; folder / "day1.txt" lets Path pick the right one, so the same program works everywhere. The Python in this app runs like Linux, so it prints slashes. A Path also does the small jobs that are easy to get wrong by hand: the extension is whatever follows the last dot, and with_suffix(".bak") swaps only that.

Writing is one call too. write_text makes the file, or replaces what was in it, and gives back how many characters it wrote; mkdir(exist_ok=True) makes a folder unless it is already there:

from pathlib import Path

Path("backup").mkdir(exist_ok=True)
out = Path("backup") / "report.final.txt"
print(out.write_text("all good\n"))
print(out.read_text(), end="")
print(out.stem, out.suffix, out.with_suffix(".bak").name)

Mistakes and edge cases.

  • building paths with +: "notes" + "day1.txt" gives notesday1.txt; join with /
  • a missing file: read_text() on a path that doesn't exist stops with a FileNotFoundError; check .exists() first, or catch it (Chapter 18)
  • write_text replaces: it doesn't add to the end; to add, read the old text and write old + new, or open(p, "a") (Lesson 20.2)
  • glob order isn't promised: the files can come in any order, so wrap it in sorted() when the order matters
  • a slash at the start: Path("notes") / "/day1.txt" throws away notes, because a path starting with / begins at the very top of the disk

Quiz

  1. What does this print?

    from pathlib import Path
    
    p = Path("photos") / "2026" / "trip.jpg"
    print(p.name, p.suffix, p.parent.name)
  2. What does this print?

    from pathlib import Path
    
    p = Path("report.final.pdf")
    print(p.stem, p.suffix)
  3. What does this print?

    from pathlib import Path
    
    p = Path("hello.txt")
    p.write_text("one")
    p.write_text("two")
    print(p.read_text())
  4. Why join paths with / instead of +?

    • Path puts in the right separator for each computer
    • / makes the file smaller
    • + only works on numbers
  5. The folder must stay "notes", as line 3 says. This should read notes/day1.txt but stops with a FileNotFoundError. Which line is wrong?

    from pathlib import Path
    
    folder = "notes"
    p = Path(folder + "day1.txt")
    print(p.read_text())

Coding tasks

  1. Write count_txt(folder): how many .txt files are in the folder folder (a string). Try it on notes, which also holds a .md file.

  2. Write line_counts(folder): a list of (file name, number of lines) pairs for every .txt file in the folder, sorted by file name.

  3. Write backup(path): copy the text of the file at path into a new file with the same name but the extension .bak (in the same folder), and return the new path as a string.