Skip to main content

How to Get a File's Name from a Path in Python with Path.name

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

photos/daisy.jpg is where a file is; daisy.jpg is what it's called. To show a file or folder's own name, for a label, a log line or a count per folder, take the last part of the path with pathlib's Path.name. This guide reads the name of four paths on Python 3.15.2.

Syntax​

Syntax
Path("<path>").name
PartWhat it means
Path("<path>")A path to a file or a folder. It doesn't have to exist
.nameThe last part of the path, as a string

The pathlib documentation defines it as "A string representing the final path component, excluding the drive and root, if any".

The Example​

Four paths: a file in a folder, a folder, the same folder written with a slash at the end, and a bare file name. The script prints each one's name in square brackets.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

names.py
from pathlib import Path

for text in ["photos/daisy.jpg", "photos/old", "photos/old/", "daisy.jpg"]:
print(f"{text}: [{Path(text).name}]")

The names.py script in a macOS-style code window: a loop over photos/daisy.jpg, photos/old, photos/old/ and daisy.jpg that prints each one with its Path(text).name in square brackets.

Step 2: Run It​

Terminal
uv run python names.py
Output
photos/daisy.jpg: [daisy.jpg]
photos/old: [old]
photos/old/: [old]
daisy.jpg: [daisy.jpg]

The terminal after uv run python names.py: daisy.jpg for photos/daisy.jpg, old for photos/old and for photos/old/, and daisy.jpg for daisy.jpg.

The file's name keeps its extension, a folder's name is just the folder, and the slash at the end of photos/old/ made no difference: Path ignores it. A bare file name is its own name. The command works unchanged in PowerShell, and on Windows Path understands backslashes in paths as well.

Common Mistakes​

MistakeWhat happensDo this instead
Splitting the text yourself: "photos/old/".split("/")[-1]It gave an empty string, [], because of the slash at the end. Path("photos/old/").name gave [old]Let Path take the path apart
Expecting the name without the extensionname keeps it: daisy.jpgUse stem, below

FAQ​

How do I get the name without the extension?​

Use stem. For Path("photos/daisy.jpg"):

stem.py
from pathlib import Path

path = Path("photos/daisy.jpg")
print(path.name)
print(path.stem)
Output
daisy.jpg
daisy

Is Path.name the same as os.path.basename?​

Not quite. For photos/daisy.jpg, both gave daisy.jpg. For photos/old/, os.path.basename() gave an empty string, '', like split() above, while Path("photos/old/").name gave old.

Conclusion​

Path(text).name returned the last part of each path: daisy.jpg for a file, old for a folder, with or without a slash at the end. For the name without its extension, use stem.

Additional Resources​