Skip to contentSkip to navigation

Module 08 · Lesson 02

Paths and Folders with pathlib

Work with files and folders through Path objects: build paths with /, read their parts, check what exists, create folders, list and search them, and read or write a file in one call.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Join paths with /
  • Take a path apart
  • List a folder in order
  • Watch a save file appear

Paths as objects

`pathlib` turns a file's address into an object that knows its name, its folder and whether it exists.

  • Path()

    Path("notes") / "today.txt" joins parts with /, on any computer.

  • Its parts

    .name, .stem, .suffix and .parent take a path apart.

  • Ask first

    .exists(), .is_file() and .is_dir() answer True or False and never crash.

  • One-call files

    write_text() and read_text() open, work and close in one line.

Paths everywhere

Any program that tidies, backs up or saves files is working with paths.

  • Photo appsChange IMG_001.jpeg into IMG_001.png with with_suffix().
  • BackupsFind every .txt in a folder with glob("*.txt") and copy it.
  • Game savesMake a saves folder the first time the game runs.
  • DownloadsSort a messy Downloads folder by each file's .suffix.

Building a path

This line describes where a file lives. Tap each part to see its job.

Part 1 of 6

Tap any part of the code below, or press Next.1 of 6 explored

path:A Path object. Nothing is created on disk yet; it is only an address.

Work with paths

Pick an example, change it, then press Run. Say what you expect to see before you press. Each Run starts with no files, so every example writes its own.

Example 1 of 6Build a path

/ joins parts. as_posix() shows the path with forward slashes on every computer.

Your turn: Add one more folder, live, between rock and the file.

Python
from pathlib import Path
folder = Path("music")
song = folder / "rock" / "track01.mp3"
print(song.as_posix())
print(song.name)
print(song.parent.as_posix())
Output
Press Run to see what it prints.

Watch a save file appear

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. from pathlib import Path
  2. base = Path("game")
  3. save = base / "slot1.txt"
  4. base.mkdir(exist_ok=True)
  5. save.write_text("stage 3", encoding="utf-8")
  6. print(save.exists(), save.suffix)
  7. print(save.read_text(encoding="utf-8"))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.The name without its ending:

from pathlib import Path
print(Path("songs/intro.mp3").stem)

0 of 6 answered

Common pathlib misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

A path is an object

pathlib is part of the standard library. Its Path class represents a location on disk. Creating a Path does not create a file; it only describes where one would be.

Try it 1: edit me, then Run
from pathlib import Path

report = Path("reports") / "2024" / "march.txt"
print(report.as_posix())    # reports/2024/march.txt
Output
Press Run to see what it prints.

The / operator joins parts into a longer path, using the right separator for the computer the program runs on. Printing a Path shows it in the local style, so on Windows you would see reports\2024\march.txt. as_posix() always gives forward slashes, which is handy when you want the same output everywhere. You can also pass a Path anywhere a file name is expected, including open().

The parts of a path

A path knows how to split itself up, so you never have to slice strings to find an extension:

Try it 2: edit me, then Run
p = Path("photos/holiday/beach.final.jpg")
print(p.name)           # beach.final.jpg   (the last part)
print(p.stem)           # beach.final       (name without the last suffix)
print(p.suffix)         # .jpg              (the extension, with its dot)
print(p.parent.name)    # holiday           (the folder that holds it)
print(p.parts)          # ('photos', 'holiday', 'beach.final.jpg')
Output
Press Run to see what it prints.

with_suffix() and with_name() return a new path with one part swapped, which is perfect for making a backup or a converted copy: p.with_suffix(".png") is photos/holiday/beach.final.png. Paths, like strings, are never changed in place.

Asking what exists

Try it 3: edit me, then Run
data = Path("data")
print(data.exists())      # does anything live here?
print(data.is_dir())      # is it a folder?
print(data.is_file())     # is it a regular file?
Output
Press Run to see what it prints.

All three return False for a path that does not exist, rather than raising an error. Check before you read when a missing file is expected, for example a settings file that is only created after the first run.

A common pattern is a file that may or may not be there yet. Checking first lets the program choose a sensible default instead of crashing:

Try it 4: edit me, then Run
settings = Path("settings.txt")
if settings.is_file():
    theme = settings.read_text(encoding="utf-8").strip()
else:
    theme = "light"
Output
Press Run to see what it prints.

The first time the program runs there is no settings file, so it uses the light theme. Once the user saves a choice, later runs read it back. The errors lessons later in this course show a second approach: try to read the file and handle the error if it is missing.

Creating folders

mkdir() creates a folder. Two arguments make it convenient:

Try it 5: edit me, then Run
Path("backup/2024/june").mkdir(parents=True, exist_ok=True)
Output
Press Run to see what it prints.

parents=True also creates any missing folders along the way, and exist_ok=True means "do not complain if it is already there". Without exist_ok, running the program twice raises FileExistsError.

Reading and writing in one call

For small text files, a Path can do the whole open, read or write, and close in one step:

Try it 6: edit me, then Run
note = Path("note.txt")
note.write_text("Water the plants\n", encoding="utf-8")
print(note.read_text(encoding="utf-8").strip())
Output
Press Run to see what it prints.

write_text replaces the file's contents, just like opening with mode "w". For appending, or for reading a large file line by line, use with note.open("a", encoding="utf-8") as f: as in the previous lesson; Path.open() takes the same modes as open().

Listing a folder

iterdir() gives every entry directly inside a folder. The order depends on the operating system and is not alphabetical, so sort the results when order matters:

Try it 7: edit me, then Run
for entry in sorted(Path("reports").iterdir()):
    kind = "folder" if entry.is_dir() else "file"
    print(entry.name, kind)
Output
Press Run to see what it prints.

Finding files by pattern

glob() finds paths that match a pattern. * matches any run of characters within one name, and ** matches any number of folders:

Try it 8: edit me, then Run
texts = sorted(Path("reports").glob("*.txt"))          # this folder only
everything = sorted(Path("reports").glob("**/*.txt"))  # all subfolders too
names = [p.name for p in texts]
Output
Press Run to see what it prints.

rglob("*.txt") is a shortcut for the second form. Like iterdir, these return their matches in no guaranteed order, so wrap them in sorted().

Removing things

unlink() deletes a file and rmdir() deletes an empty folder. Deleting is permanent, with no recycle bin, so check the path first and be especially careful inside loops.

Relative and absolute paths

A relative path such as Path("data/scores.txt") is measured from the current working directory. Path.cwd() tells you what that is, and path.resolve() turns a relative path into a full, absolute one. Absolute paths depend on the machine, so keep them out of your output and your tests; describe files relative to the project folder instead.

pathlib or plain strings?

Older code often uses the os and os.path modules with string paths, such as os.path.join("reports", "march.txt"). You will still see it, and it works. New code generally prefers pathlib, because a path's parts, checks and file operations all live on one object, and / reads naturally. Both styles can be mixed, since str(path) turns a Path into a plain string.

Syntax

The general shape of the statements in this lesson.

syntax.py
from pathlib import Path
p = Path("data") / "scores.txt"      # join parts
p.name, p.stem, p.suffix, p.parent   # parts
p.with_suffix(".bak")                # new path, other extension
p.exists(), p.is_file(), p.is_dir()
Path("a/b").mkdir(parents=True, exist_ok=True)
p.write_text("hi\n", encoding="utf-8")
p.read_text(encoding="utf-8")
sorted(Path("data").iterdir())       # entries, sorted
sorted(Path("data").glob("*.txt"))   # matches, sorted
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Organising downloads by type

Beginner

A downloads folder holds a mix of files. Create it with sample files, then report how many files there are of each extension.

Python
from pathlib import Path

downloads = Path("downloads")
downloads.mkdir(exist_ok=True)
for name in ["cv.pdf", "cat.jpg", "notes.txt", "dog.jpg", "plan.pdf", "todo.txt", "song.mp3"]:
    (downloads / name).write_text("sample", encoding="utf-8")

counts = {}
for entry in sorted(downloads.iterdir()):
    counts[entry.suffix] = counts.get(entry.suffix, 0) + 1

for suffix in sorted(counts):
    print(suffix, counts[suffix])
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The / operator builds each file path inside the folder. suffix gives the extension without any string slicing, and the dictionary counts them. Sorting both the listing and the final keys keeps the output the same on every computer.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Expecting a sorted folder listing

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
for f in Path("pics").iterdir():
    print(f.name)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Names appear in a different order on different computers

Write this instead

for f in sorted(Path("pics").iterdir()):
    print(f.name)

Why it happens

iterdir and glob return entries in whatever order the file system stores them.

In the real world

Where this shows up in software people use every day.

  1. Collecting monthly sales files

    Retail analytics

    A chain of shops drops one sales file per branch into dated folders. Each morning a script gathers every branch file in every month folder and totals them.

    Why Python fits

    The pattern **/*.txt searches every month folder at once, so a new month needs no code change. parent.name and stem pull the month and branch out of the path itself.

    Python
    from pathlib import Path
    
    for month, branch, amount in [("2024-05", "north", 120), ("2024-05", "south", 80), ("2024-06", "north", 150)]:
        folder = Path("sales") / month
        folder.mkdir(parents=True, exist_ok=True)
        (folder / f"{branch}.txt").write_text(f"{amount}\n", encoding="utf-8")
    
    total = 0
    for path in sorted(Path("sales").glob("**/*.txt")):
        amount = int(path.read_text(encoding="utf-8"))
        print(path.parent.name, path.stem, amount)
        total += amount
    print("Total:", total)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why does my path print with backslashes?

On Windows, paths use backslashes. The path is still correct. Use as_posix() if you want forward slashes in output.

Do I still need open() if I use pathlib?

Not for small files: read_text and write_text are enough. For appending or line-by-line reading, use path.open(), which works like open().

How do I get the extension without the dot?

Slice it off: p.suffix[1:] turns .pdf into pdf. For a file with no extension, suffix is an empty string, so the slice is empty too and nothing breaks.

Can a Path point at a folder that does not exist yet?

Yes. Paths are only descriptions, so you can build the full path first and create the folder with mkdir when you are ready to write into it.

Is it safe to delete files with unlink?

It is permanent. Print the paths you are about to delete first, and only delete inside folders your own program created.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 10 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.