──────────────────────────────────────

37. Build Tools for Repeated Tasks · Read the Parts of a Filename

Use pathlib to identify a file’s name, stem and extension.

Lesson files · lessons/command-line-tools/path-parts

Before you start
- Create a path from a folder name and filename with pathlib.
- Use lower() to compare text regardless of case.

By the end
- Identify the name, stem and suffix of a sample path.
- Print a lowercased suffix or the marker for a missing extension.

Where you can use it
Use the final filename and normalised extension to recognise a CSV in a list of classroom download paths.

PurePosixPath reads the parts of a path written with forward slashes. It works on a sample path as text. name gives the final filename, suffix gives its last extension including the dot, and stem gives the part of the filename before that suffix. Use lower() on the suffix before comparing extensions.

Predict
What would suffix return before lower()?
- .CSV
- CSV

Worked example (example.py)

from pathlib import PurePosixPath
path = PurePosixPath("notes/survey.CSV")
print(path.stem)
print(path.suffix.lower())


Example result
survey
.csv

Read a sample path and print its final name and lowercase suffix. Print (none) for the suffix when there is no extension.

Starter program (starter.py)

from pathlib import PurePosixPath
path = PurePosixPath("notes/survey.CSV")
print(path.stem)
print(path.suffix.lower())


Hint
Use path.name and path.suffix.lower() or "(none)".

Case 1. Try the sample
Input
class/notes.TXT
Expected output
notes.TXT
.txt

Case 2. No extension
Input
README
Expected output
README
(none)

Stretch
Investigate the difference between suffix and suffixes for report.tar.gz.

Reflect
Why can you inspect these parts without actually opening a file?

Check your prediction
.CSV The suffix includes the dot and keeps its original case.
