How to Get File Extension from Filename in Python?

Hi Python Devs,
Today’s topic is all about how to get the file extension from a filename or path in Python. If you’re working with files, understanding how to extract the file extension (like .png
, .txt
, or .csv
) is a key skill.
In this tutorial, you'll learn how to use Python’s built-in os
module to retrieve the extension of a file easily. This works for any version of Python 3.
Let’s check out a very simple example that demonstrates this concept clearly.
Example:
main.pyimport os fileName, fileExtension = os.path.splitext('demo.png') print("File Name: ", fileName) print("File Extension: ", fileExtension)Output
File Name: demo File Extension: .png
As you can see, the os.path.splitext()
method splits the full filename into two parts: the name of the file and its extension.
This is especially useful when you need to validate file types, filter specific file formats, or perform conditional operations based on file extensions.
Happy Pythonic Coding!
🧠 FAQ - Getting File Extensions in Python
- Q: How do I get the extension of a file in Python?
A: Useos.path.splitext(filename)
. It returns a tuple with the filename and the extension. - Q: Will
splitext()
work if the file has multiple dots (e.g., demo.backup.png)?
A: Yes, it only splits at the last dot, so'demo.backup.png'
returns('demo.backup', '.png')
. - Q: What is the return type of
splitext()
?
A: It returns a tuple: (filename, extension). - Q: Can I use pathlib instead of os.path?
A: Yes!Path('demo.png').suffix
from thepathlib
module will return'.png'
. - Q: How to get the file extension without the dot?
A: UsefileExtension.lstrip('.')
to remove the dot from the extension.