To remove the extension from a filename using Python, the easiest way is with the os module path.basename() and path.splitext() functions.
import os
filename = os.path.basename("C:/Users/TheProgrammingExpert/example.png")
filename_without_ext = os.path.splitext(filename)[0]
print(filename)
print(filename_without_ext)
#Output:
example.png
example
You can also use the pathlib module and Path and then access the attribute ‘stem’ to remove the extension from a filename.
from pathlib import Path
print(Path("C:/Users/TheProgrammingExpert/example.png").stem
#Output:
example
When working with files in Python, the ability to easily get the filename without the extension and remove the file extension can be useful.
With Python, there are a few ways you can remove the file extension. The easiest way is with the os module, but you can also use the pathlib module.
Using os Module to Remove Extension from Filename Using Python
The Python os module has many great functions which help us interact with the operating system of our computer.
To remove the extension from a filename using Python, the easiest way is with the os module path.basename() and path.splitext() functions.
path.basename() gets the complete filename and path.splitext() splits the filename into the filename and extension.
Below is a simple example showing you how to get the filename without file extension in Python.
import os
filename = os.path.basename("C:/Users/TheProgrammingExpert/example.png")
filename_without_ext = os.path.splitext(filename)[0]
print(filename)
print(filename_without_ext)
#Output:
example.png
example
Using pathlib Module to Remove Extension from Filename Using Python
You can also use the pathlib module to get file size in your Python code.
With the Python pathlib module, we can perform many operations to access files and directories in our environments.
You can use the pathlib module and Path, and then access the attribute ‘stem’ to remove the extension from a filename.
Below is a simple example showing you how to get remove the extension from a file using the Python pathlib module.
from pathlib import Path
print(Path("C:/Users/TheProgrammingExpert/example.png").stem
#Output:
example
Hopefully this article has been useful for you to learn how to remove the file extension from a file using Python.