Skip to content
techskilldaily.
The archiveNo. 014
A little Python

Take a filename apart.

Use pathlib to read a file’s name and extension without opening it.

2 min read 5 min to try
MAKE ROOM FORoneSMALL SKILL

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

Path

notes/meeting.txt

Properties

name: meeting.txt stem: meeting suffix: .txt

No file access is needed for these properties.

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.

A small example to try
from pathlib import Path
p = Path("notes/meeting.txt")
print(p.name)
print(p.stem)
print(p.suffix)
Your turn 5 minutes

Make it yours.

  1. Run the example without creating a file.
  2. Replace meeting.txt with archive.tar.gz.
  3. 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().

Keep this bit

Read a path before doing anything to the file.

Read more: Python · pathlib ↗

No submission needed. This one is just for you.

Another spark of curiosityCount the rows that match.