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.

def extension(x):

The split() method splits or breaks a string and returns a list of substrings.
Syntax:
string_name.split(separator,number_of_splits)
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.

ext=x.split(".",2)

The returned list is stored in a variable ext. Let’s print the value of ext.

print(ext)

['nitesh/user/codespeedy', 'py']

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[1].

Let’s see how our code looks like.

def extension(x):
    ext=x.split(".")
    print(ext)
    return (ext[1])
    
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”)

Output:

['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.
Syntax:

string_name.rindex(substring)

Let’s define a function extension1() which takes file_path as an argument and returns the required expression.

def extension1(x):

Now, let’s use rindex() method.

arr=""
ext=x.rindex(".")

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.

i.e,

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.

extension1("nitesh/user/codespeedy.txt")

Which gives the output,

Extension of the given file is: txt


Also, Learn:


Leave a Reply

Your email address will not be published. Required fields are marked *