How to Get File Extension from Filename in Python?

Published On: 25/03/2025 | Category: Python
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.py
import 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: Use os.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 the pathlib module will return '.png'.
  • Q: How to get the file extension without the dot?
    A: Use fileExtension.lstrip('.') to remove the dot from the extension.