In this article, you will learn different ways to remove file extensions in Python to make your code clear, efficient, and adaptable to various scenarios.
When working with files in Python, you may need to remove the extension from a file name. For example, you might want to display clean file names in a dashboard or process file names before saving data.
You can remove the extension from a file name in Python using the pathlib module’s .stem property (modern and recommended) or the os.path.splitext() function. Both methods safely separate the file name from its extension. For instance, "example.txt" becomes "example" after removing .txt.
Why Remove File Extensions?
Removing file extensions is common in file management scripts, automation tasks, and user interface design. And in many cases, the extension is useful for the system but unnecessary for users.

Forexample, imagine you are building a photo gallery website. The images are stored as:
beach.jpgmountains.pngsunset.jpeg
Now, if you display these names directly to users, the page may look technical and slightly untidy. Instead, you may want to show:
- Beach
- Mountains
- Sunset
So, you remove the file extension (.jpg, .png, .jpeg) before displaying the name.
The extension is important for the system because it tells the computer what type of file it is. However, for users, it is often unnecessary. Therefore, removing the extension makes the interface cleaner and more readable.
In the same way, Python allows you to separate the file name from its extension safely and efficiently.
Ways to Get File Name Without Extension in Python
In Python, there are multiple ways to cut off an extension from a file name. Let’s discuss all possible ways because each method has its own benefits.
Note that in the following codes, we are using the relative path for the filename. That’s why only the file name is written instead of the whole path. These methods will work the same for the whole path as well.
1st Method: Use Path from pathlib (Recommended)
The pathlib approach works well for large or complex projects. It improves code readability and makes maintenance easier.
Moreover, it is great for cross-platform applications. This is because pathlib handles file paths in a way that hides system-specific differences.
If your filenames contain spaces you can also remove spaces from the string (filename) before or after stripping the extension.
Syntax
Path(filename).stem
Example Code
- The
Pathclass from thepathlibmodule is used to create aPathobject fromfile_name. - The
.stemattribute of thePathobject is then accessed to get the filename without its extension. .stemworks by automatically removing the last extension from the filename, soPath("example.txt").stemreturns"example".
from pathlib import Path file_name = "example.txt" name = Path(file_name).stem print(name)
Output
example
2nd Method: Use os.path.splitext()
os.path.splitext() is a built-in Python function that splits a file path into two parts: the file name and its extension.
It is quick and reliable for removing extensions from simple file paths. Moreover, it works well for most common file types. As a result, your code stays clean and easy to maintain.
You can also limit or truncate the string (filename) before or after removing the extension.
Syntax
os.path.splitext(filename)
Example Code
- The
os.path.splitext()function works by analyzing thefile_namestring. It looks for the last occurrence of a dot (.) in the string. - It splits the string into two parts:
- The first part is everything before the last dot, which is the main filename (
name). - The second part is everything after the last dot, which is the file extension (e.g.,
.txt).
- The first part is everything before the last dot, which is the main filename (
- The function returns these two parts as a tuple. For example,
("example", ".txt"). - In the code, we assign the first part to
nameand the second part to_(a common practice for indicating a variable that won’t be used). - So this means
namenow contains only the filename without its extension. - Finally,
print(name)outputs the value stored inname, which is “example”.
import os file_name = "example.txt" name, _ = os.path.splitext(file_name) print(name)
Output
example
3rd Method: Use String rpartition()
The rpartition() method splits a string at the last dot (.). As a result, it separates the file name from its extension and returns only the name.
It is simple and works well for small scripts. Moreover, it does not require importing any extra libraries.
Syntax
filename.rpartition('.')[0]Example Code
- The
rpartition()method splits the string into three parts: the part before the last dot, the dot itself, and the part after the dot. - By using
[0], we take only the first part, which is the filename without the extension.
file_name = "example.txt"
name = file_name.rpartition('.')[0]
print(name) Output
example
4th Method: Use String split() and join()
The split() method, combined with join(), is another way to remove a file extension. First, it splits the filename at the dot (.). Then, it joins all parts except the last one. As a result, you get the name without the extension.
It works best for quick scripts. Moreover, it does not require any extra imports.
Syntax
'.'.join(filename.split('.')[:-1])Example Code
- The
split('.')method breaks thefile_namestring into a list of parts, using the dot as the separator. For"example.txt", this results in['example', 'txt']. - The
[:-1]slice removes the last element of the list, which is the extension ('txt'). - The
'.'.join()method then joins the remaining parts of the list back into a string, reconstructing the filename without the extension. - The
print(name)statement outputs the filename without its extension.
file_name = "example.txt"
name = '.'.join(file_name.split('.')[:-1])
print(name) Output
example
5th Method: Use Regular Expressions: re Module (Advanced)
Regular expressions (regex) provide a powerful and flexible way to handle strings. Therefore, they are useful for complex cases, such as filenames with multiple dots or unusual patterns.
Moreover, regex gives you more control and precision. As a result, it is better suited for advanced string handling tasks.
Syntax
re.sub(r'\.[^.]+$', '', filename)
Example Code
- The
re.sub()function is used to search for and replace parts of a string that match a specific pattern. - The pattern
r'\.[^.]+$'matches the last dot (.) and any characters following it until the end of the string. The[^.]means any character that is not a dot, and+ensures one or more of these characters are matched. - The replacement string is an empty string (
''), removing the matched extension. - The
print(name)statement then outputs the filename without its extension.
import re file_name = "example.txt" name = re.sub(r'\.[^.]+$', '', file_name) print(name)
Output
example
6th Method: Use Slicing with rfind()
The rfind() method finds the position of the last dot in the filename. Then, you can slice the string up to that position to remove the extension.
It is a lightweight solution. Moreover, it does not require importing any additional libraries.
Syntax
filename[:filename.rfind('.')]Example Code
- The
rfind('.')method searches for the last occurrence of the dot character in thefile_namestring and returns its index. - The slicing operation
file_name[:index]extracts the substring from the start up to (but not including) the last dot. - If no dot is found,
rfind()returns-1, and the entire string is returned without slicing. - The
print(name)statement outputs the filename without its extension.
file_name = "example.txt"
name = file_name[:file_name.rfind('.')]
print(name) Output
example
Comparison of Methods
Below is a table comparing the methods discussed, highlighting their pros, cons, and best use cases:
| Method | Pros | Cons | Best for |
|---|---|---|---|
Path from pathlib | Modern, readable | Requires pathlib import | Complex projects, cross-platform |
os.path.splitext() | Simple, built-in | Limited to single-dot extensions | |
String rpartition() | No imports needed | Single-dot extensions only | Simple scripts |
String split() and joining | No imports needed, flexible | Less readable for complex cases | Quick, lightweight solutions |
Regular Expressions (re module) | Handles complex cases | Requires regex knowledge | Advanced string handling |
Slicing with rfind() | No imports needed, simple | Single-dot extensions only | Lightweight, straightforward solutions |
For most real-world projects in 2026, Path from pathlib is the best choice.
Handling Files Without Extensions or Hidden Files
For files without extensions or hidden files that start with a dot (e.g., .gitignore), ensure your method can handle these edge cases. Some methods may return an empty string if there is no extension, so adding a check like if '.' in file_name can help avoid issues.
file_name = ".gitignore"
if '.' in file_name:
name = file_name[:file_name.rfind('.')]
else:
name = file_name
print(name) # Output: .gitignoreManage Filenames with Multiple Extensions
For filenames with multiple extensions (e.g., example.tar.gz), you may want to remove only the last extension or all extensions. Using rpartition() or re.sub() can control this behavior.
To remove only the last extension:
file_name = "example.tar.gz"
name = file_name.rpartition('.')[0]
print(name) Output
example.tar
To remove all extensions:
import re file_name = "example.tar.gz" name = re.sub(r'\.[^.]+$', '', file_name) print(name)
Output
example
FAQs
How to remove file name extension in Python?
The best way is to use Path(filename).stem. It is modern, readable, and works across platforms.
Does splitext() work with full file paths?
Yes. os.path.splitext() works on both filenames and complete file paths. It separates the path into name and extension parts.
How do I remove multiple extensions like .tar.gz?
By default, Path(filename).stem removes only the last extension. However, to remove all extensions, you need custom processing or repeated methods.
Do these methods rename the actual file?
No. These methods only modify the filename string. However, to rename the real file on disk, use Path.rename() or os.rename().
What is strip() in Python?
The strip() method removes leading and trailing characters from a string. Leading means at the beginning, and trailing means at the end. If no character is specified, it removes whitespace by default.
What is the best method to remove file extensions in Python?
The best method is Path(filename).stem. It is simple, clean, and modern. It also works well in most real-world projects.
Conclusion
Removing file extensions can be done in multiple ways, each with its own benefits. Choose the method that best fits your project’s needs. Just as there are different ways to peel an apple, select the one that works best for your task. Efficient code practices often involve tracking the performance of scripts when removing an extension from a file name. You can learn how to print elapsed time in Python to evaluate how quickly these operations run.
For more articles on such useful scenarios and handling common errors in Python, check out our Python tutorial series by Syntax Scenarios.
