How to Remove File Extension in Python (6 Easy Ways)

Get file name without extension in python

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.

Example showing how to remove file extension in Python for cleaner display names

Forexample, imagine you are building a photo gallery website. The images are stored as:

  • beach.jpg
  • mountains.png
  • sunset.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

  1. The Path class from the pathlib module is used to create a Path object from file_name.
  2. The .stem attribute of the Path object is then accessed to get the filename without its extension.
  3. .stem works by automatically removing the last extension from the filename, so Path("example.txt").stem returns "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

  1. The os.path.splitext() function works by analyzing the file_name string. It looks for the last occurrence of a dot (.) in the string.
  2. 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).
  3. The function returns these two parts as a tuple. For example, ("example", ".txt").
  4. In the code, we assign the first part to name and the second part to _ (a common practice for indicating a variable that won’t be used).
  5. So this means name now contains only the filename without its extension.
  6. Finally, print(name) outputs the value stored in name, 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

  1. The rpartition() method splits the string into three parts: the part before the last dot, the dot itself, and the part after the dot.
  2. 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

  1. The split('.') method breaks the file_name string into a list of parts, using the dot as the separator. For "example.txt", this results in ['example', 'txt'].
  2. The [:-1] slice removes the last element of the list, which is the extension ('txt').
  3. The '.'.join() method then joins the remaining parts of the list back into a string, reconstructing the filename without the extension.
  4. 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

  1. The re.sub() function is used to search for and replace parts of a string that match a specific pattern.
  2. 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.
  3. The replacement string is an empty string (''), removing the matched extension.
  4. 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

  1. The rfind('.') method searches for the last occurrence of the dot character in the file_name string and returns its index.
  2. The slicing operation file_name[:index] extracts the substring from the start up to (but not including) the last dot.
  3. If no dot is found, rfind() returns -1, and the entire string is returned without slicing.
  4. 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:

MethodProsConsBest for
Path from pathlibModern, readableRequires pathlib importComplex projects, cross-platform
os.path.splitext()Simple, built-inLimited to single-dot extensions
String rpartition()No imports neededSingle-dot extensions onlySimple scripts
String split() and joiningNo imports needed, flexibleLess readable for complex casesQuick, lightweight solutions
Regular Expressions (re module)Handles complex casesRequires regex knowledgeAdvanced string handling
Slicing with rfind()No imports needed, simpleSingle-dot extensions onlyLightweight, 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: .gitignore

Manage 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.

Scroll to Top