Table of Contents
Introduction to get file extension in Python
When we are starting to write code in any programming language then we need to save the file at a location. For that purpose, we specify the path. Pathname consists of an extension of the file, file name, and file location. Like every programming language, Python also has file extensions known by (.py). All the python files are saved with the .py extension and other scripts are also converted into this extension. In this tutorial, we will discuss how to get file extensions in Python.
We will cover various methods through which we can get the file extension including
rpartition() method by taking various examples. In a nutshell, this tutorial will contain all the necessary details that you need to know in order to get a file extension in Python.
Getting started with different get file extension methods in Python
When we start coding in python using any editor such as Visual Studio Code then we need to write the code first then save the code with the Python extension .py or we first save the document with the .py extension then start coding. Though there are various methods that we can use to get the file extension in Python, in this article we will look at six different ways to get a filename without extension.
Method-1: Get file extension in Python using splitex() method
This is the first method to get file names without using extensions. We can extract file extensions using the Python OS module
splitext() function. This function splits the file path string into the file name and file extension into a pair of root and extension such that when both are added then we can retrieve the file path again (file_name + extension = path). The following is the simple syntax of
This function is preferred to use when the OS module is being used already.splitex() function gets an argument where the pathname is mentioned and it returns a tuple including root names and separated extension.
Example-1 Get file extension in Python using splitex() method
Now let us take an example and see how we can use the
splitex() method to find the file extension in Python. See the following program.
# importing os module import os # this will return a tuple of root and extension split_tup = os.path.splitext('file.csv') # printing print(split_tup) # extract the file name and extension file_name = split_tup file_extension = split_tup # priting print("File Name: ", file_name) print("File Extension: ", file_extension)
('file', '.csv') File Name: file File Extension: .csv
Here the output will be the name and extension of the file.
Method-2: Get file extension in Python using the split() function
Another method that we can use to find the file extension is
split() method. We will use this function in a similar way we used
splitext() above to get file extension in Python. In this case, we will not use the os module instead we will just call the
split() function. The following is the simple syntax of the split function
Name = directory.split(“.”) Name.split(“/”)
We will use the split method two times in order to get the only extension part of the file from the full directory.
Example-2 Get file extension in Python using the split() function
Initially, we will split the extension and the remaining pathname. Afterward, we will split the extension of the file. We will use “.” as a separator while using the first split function and will use “/” as a separator while using the second split function. In this case, after the first splitting, we will store the output into variable ‘name’. Then we shall split the first item of the list ‘name’ by using ‘name.split()’ with forwarding slash as the separator. Then we will print the last item of the list ‘filename’.
# declaring the directory directory = '/Users/Programs/Directory/file.csv' # using . separator to split name = directory.split('.') # using / separator to split # get file extension in Python filename = name.split('/') # printing print(filename[-1])
In this example, we are first declaring the directory using the variable directory. Next, we are splitting for the first time using. separator and in the next line we are splitting again using forward slash.
Method-3: Get file extension in Python using the rfind() function
Apart from the above-mentioned methods, we can also use
rfind() function to separate pathname and the extension. This function is used to find the last occurrence of the given value.
string.rfind(value, start, end)
In this case, a value is an item whose last occurrence has to be returned. the start and end represent the starting and ending positions while searching the string. By default, the start value is 0, and the end value is the length of the string.
Example-3 Get file extension in Python using the rfind() function
Now let us take an example and see how we can use the
rfind() method to find the file extension in Python. In this situation, we will call the
rfind() function using directory
rfind(). Inside the
rfind() function, we will pass the dot ‘.’ as the value. We will save the index of the dot character into a variable named ‘index’. Then, we will print the string ‘directory’ from the 0th character to the value of ‘index’.See the python program below:
#declaring the directory directory = '/Users/Programs/Directory/file.csv' # splitting using . separator # Get file extension in Python index = directory.rfind(".") # printing print(directory[index:])
Here, in the first line, we are declaring the directory using the directory variable. In the second line, we are using the "." operator to split and we are also using
Method-4: Get file extension in Python using basename() function
Similar to the
splitext() function, we will import the os module in order to get file extension using the basename() function. We should have to pass the complete pathname into the
basename() function. Using the
basename() function, we can get the base name of the file from the entire directory name. Here is the syntax of the base function:
The output of ‘os.path.basename(directory)’ will be ‘file.csv’. So, we will call the split function and pass the dot character as the separator. That will return a list containing [ ‘file’ , ‘csv’ ]. So we will print the first item of that list.
Example-4 Get file extension in Python using basename() function
Now let us take an example and see how
basename() function works. See the example below:
# importing os import os # declaring directory directory = '/Users/Programs/Directory/file.csv' # printing output # get file extension in Python print(os.path.basename(directory).split('.'))
Here in the first line, we are importing the os module and in the second line, we are defining the directory and assigning it to the variable directory. In the third line, we are printing the file name using the
Method-5: Get file extension in Python using the pathlib.Path.stem() function
The pathlib module in python is used to deal with the file paths. When we don’t want to get the complete path, we can use
pathlib.Path.stem(). Using the stem property, we will get the file name without its extension. The following is the simple syntax of the path method which is used to find the extension.
This method returns the file extension.
Example-5 Get file extension in Python using the pathlib.Path.stem() function
Initially, we have to import the pathlib module then we have to pass the ‘directory’ inside the
pathlib.Path() function. Before using pathlib module, make sure that you have installed it on your system. You can use pip command to install this module as shown below:
pip install pathlib
Once have successfully installed the pathlib library, then we can use it to find the file name and extension. Here we need to use the stem property. Because
pathlib.Path().suffix method of the Pathlib module can be used to extract the extension of the file path. This method will return the file name as shown below:
# importing pathlib module import pathlib # declaring directory directory = '/Users/Programs/Directory/file.csv' # defining filename using pathlib.Path() function # get file extension in Python filename = pathlib.Path(directory).stem # printing print(filename)
Here in the first line, we are importing the pathlib module and then we are declaring the directory using the variable directory. In the third line we are defining the filename using the function
pathlib.Path(). In the above example, we are using the stem as a suffix to extract the extension of the path. We can use the pathlib function without using the stem suffix. Given below is an example.
# importing the module import pathlib # using suffix # Get file extension in Python file_extension = pathlib.Path('file.csv').suffix # printing print("File Extension: ", file_extension)
File Extension: .csv
In this example, we are not using stem instead we are using a suffix to extract the extension of the path.
Get file extension in Python using rpartition() method
rpartition()function splits a given string into three parts. One part will be the separator and the other two parts will be the strings to the left and the right side of the separator. The Syntax of the
rpartition() function is given below:
function in Python split the given string into three parts.
rpartition() starts looking for a separator from the right side, till the separator is found and returns a tuple that contains part of the string before the separator, the argument of the string, and the part after the separator. It returns the part of the string before the separator, the separator parameter itself, and the part after the separator if the separator parameter is found in the string. It returns two empty strings, followed by the given string if the separator is not found in the string
Example-6 Get file extension in Python using rpartition() method
let us take an example and see how we can find the
rpartition() method to get the file extension in Python. See the python program below
# declaring directory directory = '/Users/Programs/Directory/file.csv' # printing # get file extension in Python print(directory.rpartition('.'))
Here in the first line, we are declaring the directory using the variable directory. In the second line we are printing the directory using the rpartition() function.
In this article, we have discussed different ways to get the python extensions. Basically, we used six different functions in Python to get the Python extensions. For example
basename() functions, where we imported the module known as os to get the filename and its extension. In other cases, we imported a module known as pathlib to extract the directory and find out the name of the file and its extension. We used the
pathlib.Path() function to extract the directory and find the file name. Furthermore, we just used functions such as
split() functions to find the file name and its extension. To summarize, this tutorial contains all the necessary and important python methods that can be used to find the extension of a file in Python.
Further Reading Section