How to get Extension of a file in Python
File extension indicates the format of a file. For example, .py indicates a Python file, .txt indicates a Text file, .pdf indicates a PDF file and many more.
In this tutorial, we will learn how do we get the extension of a file in Python. There are two methods for getting the file extension that we are going to learn today. So, Let’s get started.
Find File extension in Python
Method 1: Using split() method
First of all, we define a function extension() which takes file_name/file_path as a parameter and returns the file extension.
The split() method splits or breaks a string and returns a list of substrings.
A separator is something from where the string is split. By default it is whitespace. number_of_splits indicates the number of times you want your string to split.
Now let’s try.
The returned list is stored in a variable ext. Let’s print the value of ext.
Now since we have split our string into 2 parts, the index 1 of list ext contains the file extension. So our function will return ext.
Let’s see how our code looks like.
def extension(x): ext=x.split(".") print(ext) return (ext) print("Extension of the given file is:",extension("nitesh/user/codespeedy.py"))
The print statement prints the returned value from the function that we called using the statement, extension(“nitesh/user/codespeedy.py”)
['nitesh/user/codespeedy', 'py'] Extension of the given file is: py
Method 2: Using rindex() method
rindex() method returns the last index of a substring.
Let’s define a function extension1() which takes file_path as an argument and returns the required expression.
Now, let’s use rindex() method.
We have declared an empty string arr. We have stored the returned value of rindex() in ext.
Now, the required extension is after the index ext till the end.
for i in range(ext+1,len(x)): arr=arr+x[i]
We have concatenated i with the empty string arr so that after the end of for loop, arr will contain the file extension.
Finally, we print the value of arr.
print("Extension of the given file is:",arr)
Our final code looks like this.
def extension1(x): arr="" ext=x.rindex(".") for i in range(ext+1,len(x)): arr=arr+x[i] print("Extension of the given file is:",arr)
Now, let’s call our function and pass the path_name.
Which gives the output,
Extension of the given file is: txt