How to Extract the File Extension using Python

Here are 3 ways to extract the file extension using Python:

(1) Extract the file extension with the dot:

import os.path
my_path = r'path where the file is stored\file name.file extension'
ext = os.path.splitext(my_path)[1]
print(ext)

(2) Extract the file extension without the dot:

import os.path
my_path = r'path where the file is stored\file name.file extension'
ext = os.path.splitext(my_path)[1][1:]
print(ext)

(3) Extract both the root and the file extension:

import os.path
my_path = r'path where the file is stored\file name.file extension'
ext = os.path.splitext(my_path)
print(ext)

Next, you’ll see how to apply each of the 3 scenarios above using practical examples.

3 Scenarios to Extract the File Extension using Python

Scenario 1: Extract the file extension with the dot

Under the first scenario, you’ll observe how to extract the file extension with the dot.

To start with a simple example, let’s suppose that a text file (called ‘Products‘) is stored under the following path:

C:\Users\Ron\Desktop\Test

You can then use the following template to extract the file extension with the dot using Python:

import os.path
my_path = r'path where the file is stored\file name.file extension'
ext = os.path.splitext(my_path)[1]
print(ext)

For our example:

  • The path where the file is stored is: C:\Users\Ron\Desktop\Test
  • The file name is: Products
  • The file extension for a text file is: txt

Therefore, the complete code to extract the file extension with the dot is:

import os.path
my_path = r'C:\Users\Ron\Desktop\Test\Products.txt'
ext = os.path.splitext(my_path)[1]
print(ext)

You’ll then get “.txt” as follows:

.txt

Scenario 2: Extract the file extension without the dot

What if you’d like to extract the file extension without the dot?

In that case, you may use the template below:

import os.path
my_path = r'path where the file is stored\file name.file extension'
ext = os.path.splitext(my_path)[1][1:]
print(ext)

For our example:

import os.path
my_path = r'C:\Users\Ron\Desktop\Test\Products.txt'
ext = os.path.splitext(my_path)[1][1:]
print(ext)

You’ll now get the “txt” file extension without the dot:

txt

Scenario 3: Extract both the root and the file extension

For the final scenario, you may use the syntax below in order to extract both the root and the file extension:

import os.path
my_path = r'path where the file is stored\file name.file extension'
ext = os.path.splitext(my_path)
print(ext)

Here is the complete code for our example:

import os.path
my_path = r'C:\Users\Ron\Desktop\Test\Products.txt'
ext = os.path.splitext(my_path)
print(ext)

And here is the result:

('C:\\Users\\Ron\\Desktop\\Test\\Products', '.txt')

Finally, you may check the os.path Documentation to learn more about os.path.splitext.