How to Get a File's Name from a Path in Python with Path.name
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
Path("<path>").name
| Part | What it means |
|---|---|
Path("<path>") | A path to a file or a folder. It doesn't have to exist |
.name | The 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
from pathlib import Path
for text in ["photos/daisy.jpg", "photos/old", "photos/old/", "daisy.jpg"]:
print(f"{text}: [{Path(text).name}]")

Step 2: Run It
uv run python names.py
photos/daisy.jpg: [daisy.jpg]
photos/old: [old]
photos/old/: [old]
daisy.jpg: [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
| Mistake | What happens | Do 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 extension | name keeps it: daisy.jpg | Use stem, below |
FAQ
How do I get the name without the extension?
Use stem. For Path("photos/daisy.jpg"):
from pathlib import Path
path = Path("photos/daisy.jpg")
print(path.name)
print(path.stem)
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
- PurePath.name — the last part of a path.
- PurePath.stem — the name without its extension.
