Take a filename apart.
Use pathlib to read a file’s name and extension without opening it.
A path is a description of a location.
The text “notes/meeting.txt” contains several useful pieces: a folder, a filename, and an extension. You do not need to open the file to examine those pieces. Python’s pathlib gives them readable names.
Path(...).name returns the final filename. stem removes the last suffix from that name, and suffix returns that final suffix including its dot. The example works even when no meeting.txt file exists, because it only examines the path.
Parts of a path
notes/meeting.txt
name: meeting.txt stem: meeting suffix: .txt
A label is not a file inspection.
An extension is a naming convention. Calling a file report.pdf does not prove its bytes form a valid PDF. Here we are practicing reading a name, not checking the contents or converting a format.
Try “archive.tar.gz” as the last part of the path. The stem becomes archive.tar and the suffix becomes .gz. That result is useful: it reminds you that suffix means the final extension, not everything after the first dot.
from pathlib import Path
p = Path("notes/meeting.txt")
print(p.name)
print(p.stem)
print(p.suffix)Make it yours.
- Run the example without creating a file.
- Replace meeting.txt with archive.tar.gz.
- Compare the name, stem, and suffix results.
What changed when you tried it?
A little nudge
These properties inspect the path text; they do not read the file.
What to look for
The original output is meeting.txt, meeting, and .txt on separate lines. For archive.tar.gz, stem is archive.tar and suffix is .gz.
Take it one small step further
Try a filename with no dot and inspect its empty suffix using repr().
Read a path before doing anything to the file.
Read more: Python · pathlib ↗
No submission needed. This one is just for you.