Get File Name Without Extension in Python
In this article
To get a file name without its extension in Python, use the stem attribute from pathlib.Path or the splitext() function from os.path. Both are built-in, require no extra packages, and handle edge cases like hidden files and multiple dots correctly. This guide covers both methods, common pitfalls, and troubleshooting.
What You'll Need
- Python 3.4 or later (for
pathlib;os.pathworks in all versions) - A basic understanding of Python variables and functions
- No external libraries required
Step-by-Step
- Decide which method fits your use case. If you're working with file paths as strings, both
os.path.splitext()andpathlib.Path.stemwork.pathlibis more modern and object-oriented, whileos.pathis traditional and works with plain strings. - Import the required module.
- For
pathlib:from pathlib import Path - For
os.path:import os
- For
- Create a path object or use a string.
- With
pathlib:p = Path('/home/user/data/file.txt') - With
os.path:file_path = '/home/user/data/file.txt'
- With
- Extract the stem (name without extension).
pathlib:name_without_ext = p.stem→ returns'file'os.path:name_without_ext = os.path.splitext(os.path.basename(file_path))[0]→ returns'file'
os.path.splitext()returns a tuple(root, ext). The first element is the full path without the extension, so you needos.path.basename()first to get just the file name. - Handle files with multiple dots. Both methods treat the last dot as the extension separator. For
archive.tar.gz,Path.stemgives'archive.tar'andsplitext()[0]gives'archive.tar'. If you need the first part only, usep.name.split('.')[0](but be careful with hidden files). - Handle hidden files (e.g.,
.bashrc). Both methods treat the leading dot as part of the name, not an extension. SoPath('.bashrc').stemreturns'.bashrc', andos.path.splitext('.bashrc')[0]returns'.bashrc'. That's usually what you want. - Use the result in your code. The extracted name is a string; you can print it, use it in comparisons, or build new paths with it.
Common Mistakes
- Using
os.path.splitext()withoutbasename(). If you doos.path.splitext('/path/file.txt')[0], you get'/path/file', not just'file'. Always applyos.path.basename()first. - Forgetting that
splitext()returns a tuple. Accessing[0]is essential; using the whole tuple as a string will cause errors. - Assuming the extension is always after the last dot. This is true for both methods, but if you have a file like
my.file.name, the extension is.name, and the stem ismy.file. If that's not what you expect, you need a custom split. - Using
os.path.splitext()on a path with no directory. It still works, but you get the whole string as the root. For example,os.path.splitext('file.txt')[0]returns'file'correctly.
Tips
- Prefer
pathlibin new code because it's more readable and consistent. It also works withPathobjects that have methods like.parentand.suffix. - If you need the extension separately, use
p.suffix(pathlib) oros.path.splitext(file_path)[1]. - For working with multiple files, combine with
os.listdir()orPath.glob()to iterate and extract names. - Remember that file names are case-sensitive on Linux/macOS but not on Windows. Your code should not rely on case for extension detection.
Troubleshooting
- Getting an empty string. If the file has no extension (e.g.,
README), both methods return the whole name as the stem. That's correct. If you get an empty string, you might be usingsplitext()[1](the extension) instead of[0]. - Getting the full path instead of just the name. This happens when you use
splitext()withoutbasename(). Fix by applyingos.path.basename()first. - AttributeError: 'str' object has no attribute 'stem'. You're calling
Path.stemon a string, not aPathobject. Convert it first:Path(file_path).stem. - Unicode or special characters in file names. Both methods handle Unicode fine. If you get encoding errors, ensure your script declares the correct encoding (usually UTF-8).
- File names with trailing dots or spaces (Windows). Windows strips trailing dots and spaces from file names. If you're testing, be aware that Windows may not preserve them. On Linux/macOS, they are valid, and
splitext()will treat the last dot as the extension separator.
Frequently Asked Questions
How do I get the file name without extension from a full path?
Use Path(full_path).stem or os.path.splitext(os.path.basename(full_path))[0]. Both return just the name without directory or extension.
What if the file has no extension?
Both methods return the full name as the stem. For example, Path('README').stem returns 'README'. That's usually the desired behavior.
How do I handle files with multiple dots like 'archive.tar.gz'?
By default, both methods remove only the last extension, giving 'archive.tar'. If you want only 'archive', use Path('archive.tar.gz').name.split('.')[0], but be cautious with hidden files (e.g., .bashrc would give an empty string).
Is there a difference between pathlib and os.path for this task?
Functionally, no. pathlib is more modern and object-oriented, while os.path works with plain strings. Both are built-in and equally reliable.
Can I get the extension as well?
Yes. With pathlib, use p.suffix (e.g., '.txt'). With os.path, use os.path.splitext(file_path)[1].
Does this work on Windows paths?
Yes. Both pathlib and os.path handle Windows paths correctly when you use the appropriate path format (e.g., C:\Users\file.txt). In pathlib, you can use Path(r'C:\Users\file.txt').