Question
How can I get the filename without its extension from a file path in Python?
For example:
path = "/path/to/some/file.txt"
I want the result to be:
"file"
Short Answer
By the end of this page, you will understand how to extract just the filename stem from a full file path in Python. You will learn the most common approaches using pathlib and os.path, see how they behave with different filenames, and understand which option is usually best in modern Python code.
Concept
In Python, a file path often contains several parts:
- directories:
/path/to/some/ - filename:
file.txt - extension:
.txt
When you want only the filename without its extension, you are usually looking for the file's stem.
This matters because many programs need to:
- generate output filenames
- display a clean name to users
- group files by base name
- rename or transform files
- process uploaded files safely
Python gives you two common ways to do this:
pathlib, which is the modern, object-oriented approachos.path, which is the older but still widely used approach
For most new Python code, pathlib is the clearest choice.
A key detail: removing an extension is not the same as removing text manually. File paths can be tricky because:
- different operating systems use different path styles
- some files have multiple dots, like
archive.tar.gz - some files have no extension at all
- hidden files on Unix may start with a dot, like
.env
Using Python's path tools is safer and clearer than splitting strings by hand.
Mental Model
Think of a file path like a mailing address:
- the folders are the street and city
- the filename is the recipient
- the extension is a label attached to the name
If the full path is:
"/path/to/some/file.txt"
then:
/path/to/some/is the locationfile.txtis the full filenamefileis the core name you want.txtis the extension
Your job is to ask Python: "Give me the name part, but leave off the extension label."
Syntax and Examples
The modern Python way is to use pathlib.
Using pathlib
from pathlib import Path
path = Path("/path/to/some/file.txt")
name_without_extension = path.stem
print(name_without_extension)
Output:
file
Why this works
Path(...)turns the string into a path object.stemreturns the filename without the final extension
Using os.path
import os
path = "/path/to/some/file.txt"
filename = os.path.basename(path)
name_without_extension = os.path.splitext(filename)[0]
print(name_without_extension)
Output:
file
Why this works
os.path.basename(path)gets
Step by Step Execution
Consider this example:
from pathlib import Path
path = Path("/path/to/some/file.txt")
result = path.stem
print(result)
Here is what happens step by step:
- Python imports
Pathfrom thepathlibmodule. Path("/path/to/some/file.txt")creates a path object representing that file path.path.stemasks for the filename without its final extension.- Python looks at the last part of the path, which is
file.txt. - It removes the final extension
.txt. - The result becomes
file. print(result)outputs:
file
Traceable example with multiple paths
from pathlib import Path
paths = [
"/a/b/photo.jpg",
"/a/b/archive.tar.gz",
"/a/b/readme",
]
for p paths:
path = Path(p)
(path.name, , path.stem)
Real World Use Cases
This concept appears often in real programs.
Common uses
- Batch file processing: read all
.csvfiles and create output files using the same base name - Image conversion: turn
photo.pngintophoto.jpg - Upload systems: display a clean filename to users without the extension
- Report generation: convert
report.docxintoreport.pdf - Logging and exports: derive related filenames like
data.json→data_backup.json
Example: creating an output filename
from pathlib import Path
input_path = Path("/images/photo.png")
output_name = input_path.stem + ".jpg"
print(output_name)
Output:
photo.jpg
Example: labeling imported files
from pathlib import Path
files = [
"/uploads/alice_resume.pdf",
,
]
file_path files:
(Path(file_path).stem)
Real Codebase Usage
In real projects, developers usually do not split file paths manually. They rely on pathlib or os.path because those tools are clearer and handle edge cases better.
Common patterns
1. Build derived filenames
from pathlib import Path
source = Path("report.csv")
backup = source.with_name(source.stem + "_backup.csv")
print(backup)
This pattern is useful when generating related files.
2. Validate before processing
from pathlib import Path
path = Path("invoice.pdf")
if path.suffix != ".pdf":
raise ValueError("Expected a PDF file")
print(path.stem)
This is a simple validation pattern.
3. Process many files in a loop
from pathlib import Path
for path in Path("data").glob("*.json"):
print(path.stem)
This is common in scripts and data pipelines.
Common Mistakes
Beginners often try to solve this as a plain string problem. That can work sometimes, but it often breaks on edge cases.
Mistake 1: Splitting on /
Broken example:
path = "/path/to/some/file.txt"
name = path.split("/")[-1].split(".")[0]
print(name)
Why this is risky:
- assumes
/is the separator - breaks more easily with unusual filenames
- becomes hard to read
Better:
from pathlib import Path
print(Path(path).stem)
Mistake 2: Removing everything after the first dot
Broken example:
filename = "archive.tar.gz"
name = filename.split(".")[0]
print(name)
Output:
archive
Why this is wrong:
- it removes too much
- many files have multiple dots
Comparisons
pathlib vs os.path
| Approach | Example | Style | Best for |
|---|---|---|---|
pathlib | Path(path).stem | Modern, object-oriented | Most new Python code |
os.path | os.path.splitext(os.path.basename(path))[0] | Older, function-based | Existing codebases using os.path |
.name vs .stem vs .suffix
| Property |
|---|
Cheat Sheet
Quick reference
Modern approach
from pathlib import Path
Path("/path/to/file.txt").stem
# file
Older approach
import os
os.path.splitext(os.path.basename("/path/to/file.txt"))[0]
# file
Useful pathlib properties
from pathlib import Path
p = Path("/path/to/file.txt")
p.name # file.txt
p.stem # file
p.suffix # .txt
p.parent # /path/to
Important rules
.stemremoves only the last extension- files with no extension return their full name
- hidden files like
.envstay.env - prefer
pathlibin modern Python code - avoid manual string splitting for paths
Edge cases
FAQ
How do I get a filename without extension in Python?
Use pathlib:
from pathlib import Path
Path("/path/to/file.txt").stem
This returns file.
What is the difference between stem and name in Python?
namegives the full filename, such asfile.txtstemgives the filename without the final extension, such asfile
Does Path.stem remove all extensions?
No. It removes only the final extension.
from pathlib import Path
print(Path("archive.tar.gz").stem)
# archive.tar
Should I use pathlib or os.path?
For new code, is usually easier to read and use. is still fine, especially in older codebases.
Mini Project
Description
Build a small Python utility that takes a list of file paths and prints a clean report showing each original path, its filename, and its filename without the extension. This demonstrates practical path parsing and helps reinforce the difference between full paths, names, and stems.
Goal
Create a script that extracts filename stems from multiple file paths using pathlib.
Requirements
- Create a list containing at least four file paths
- For each path, display the full filename and the filename without the extension
- Use
pathlib.Pathin the solution - Include at least one file with multiple dots and one file with no extension
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.