How to get file extension python

get file extension python

In this tutorial, we will be solving a program for how to get file extension in python. We will be solving the above problem statement in 4 ways.

Method 1 - Using os.path.splitext() to get file extension Python

The os.path is a pre-defined python module that has utility functions to manipulate OS file paths. These functions are used for opening, retrieving, saving, and updating information from the file path. To know more about os.path module and its function you read this.

To get file extension in Python we can use splitext() method present in the os.path module. The splittext() method returns a tuple that contains the root file path and extension of the file.

Python code

# importing os.path
import os.path

file_name = "projects/project_name/specs.txt"

#using splitext()
file_root = os.path.splitext(file_path)[0]
file_extension = os.path.splitext(file_path)[1]

print("Root Path of file:", file_root)
print("File Extension:", file_extension)

Output:

Root Path of file: projects/project_name/specs

File Extension: .txt

Method 2 - Using pathlib.Path().suffix to get file extension Python

pathlib.Path().suffix method of Pathlib module is used to retrieve file extension from the given input file path. 

pathlib.Path().suffix method takes file name as input and returns the extension of the file including  . at the beginning.

import pathlib

file_name = "projects/project_name/specs.txt"

# using pathlib.Path().suffix
file_extension = pathlib.Path(file_name).suffix
print("File extension:", file_extension)

Output:

File Extension:  .txt

Method 3 - Using split() to get file extension Python

We can get the file extension by using split() method. By using split() method we can file extension without .

file_name = "projects/project_name/specs.txt"

# using split
file_extension = file_name.split(".")[-1]
print("File extension:", file_extension)

Output:

File Extension:  txt

Method 4 - Using regex to get file extension Python

We can get file extension in python by applying regex expression on the file path.

import re

file_name = "projects/project_name/specs.txt"

# using regex
file_extension = re.search(r"\.([^.]+)$", file_name).group(1)

print("File extension:", file_extension)

Output:

File Extension:  txt

Conclusion

Hence by using os.path.splitext(), pathlib.Path().suffix, regex, or split() method we can get file extension in python.