How to get file extension in Python?

Records are utilized for putting away data with the capacity to peruse and compose on them. The tasks which can be performed on documents in python are – perused, compose, open, close, rename and erase. With the assistance of documents, we can store data inside the PC’s stockpiling. Each record has a pathname that tells about the area at which the document is put away. The pathname comprises of data about the catalog where the document is put away, the name of the record, and the augmentation with which the record is put away. In this article, we will be taking a gander at six unique routes in python to get filename without expansion.

How to get the filename?

As referenced previously, a pathname comprises of three sections – the augmentation of the record, the filename, and the document’s area. To begin with, we should isolate the pathname and the augmentation. Then, at that point, from the pathname, we will isolate the filename with the registry way. We will be checking out 6 different ways in python to get filename without augmentation.

  • Utilizing splitext()
  • With the split() work
  • Utilizing find()
  • Basename() work
  • Utilizing pathlib.Path.stem()
  • By the rpartition() work
  • Additionally, Read | Apex Ways to Get Filename From Path in Python

1. Utilizing splitext() to Get Filename Without Extension in Python

The splitext() strategy can be utilized to get filename in python without expansion. The strategy is available in the os module of python. Utilizing os.path module, we can utilize it to work with pathnames in python. With splitext(), we can part the whole pathname into two sections – the expansion and the root.

The language structure of splitext() technique is:

os.path.splitext(path)

The capacity takes the pathname as a contention and returns a tuple containing the isolated augmentation and root names.

Give us carry out the capacity access python. To begin with, we will import the os module.

import os

We have a variable named ‘catalog’ which contains the total way of out document.

index = ‘/Users/Programs/Directory/program1.csv’

Presently, we will call the splitext() strategy by os.path.splitext(). We will pass the variable ‘registry’ inside the splitext() strategy. Since the strategy produces a tuple containing two sections, we will save the augmentation into a variable named ‘expansion’ and the remainder of the way into a variable named ‘pathname’.

pathname, augmentation = os.path.splitext(directory)

On the off chance that we attempt to print the result of os.path.splitext(), the tuple returned would be:

(‘/Users/Programs/Directory/program1’, ‘.csv’)

Presently, we will part the variable ‘way’ with the forward cut as the separator.

filename = pathname.split(‘/’)

From that point onward, we will print the last thing of the rundown ‘filename’, which will be the real filename.

print(filename[-1])

The result is:

program1

The whole code is:

import os
 
directory = '/Users/Programs/Directory/program1.csv'
pathname, extension = os.path.splitext(directory)
filename = pathname.split('/')
print(filename[-1])

import os

registry = ‘/Users/Programs/Directory/program1.csv’

pathname, augmentation = os.path.splitext(directory)
filename = pathname.split(‘/’)

print(filename[-1])

Here, assuming you need the total pathname, you can just skirt parting the variable ‘pathname’ and straightforwardly have it as the filename.

2. With the split() strategy to Get Filename Without Extension in Python

Like the splitext() strategy, we can likewise utilize the split() technique to get filename without augmentation. For utilizing the split() work, there is no compelling reason to import the os module. We should call the split() work twice.

In the first place, we will part the augmentation and the remainder of the pathname. Then, at that point, we will part the augmentation of the record. The separator for the principal split() capacity will be the ‘.’ character and the separator for the subsequent split() capacity will be the forward-slice ‘/’.

Here, after the first parting, we will store the result into variable ‘name’. Then, at that point, we will part the principal thing of the rundown ‘name’ by utilizing ‘name[0].split()’ with forward slice as the separator. Then, at that point, we will print the last thing of the rundown ‘filename’.

1
2
3
4
5
6
directory = '/Users/Programs/Directory/program1.csv'
name = directory.split('.')
filename = name[0].split('/')
print(filename[-1])

The output is:

program1

3. Utilizing rfind() to Get Filename Without Extension in Python

We can likewise utilize the rfind() strategy to part the filename to isolate the pathname and the augmentation. The capacity rfind() will track down the last event of the given worth.

The linguistic structure of the rfind() work is:
string.rfind(value, start, end)
We can all the rfind() technique with a string. Here, a worth is a thing whose last event must be returned. The beginning and end address the beginning and finishing positions while looking through the string. Of course, the beginning worth is 0, and the end esteem is the length of the string.

Here, we will call the rfind() work utilizing directory.rfind(). Inside the rfind() work, we will pass the speck ‘.’ as the worth. We will save the record of the spot character into a variable named ‘list’. Then, at that point, we will print the string ‘registry’ from the 0th person to the worth of ‘file’.

1
2
3
directory = '/Users/Programs/Directory/program1.csv'
index = directory.rfind(".")
print(directory[:index])

The output is:

/Users/Programs/Directory/program1

4. Utilizing Basename() capacity to Get Filename Without Extension in Python

We can likewise utilize the basename() work from the os module to isolate the filename. With the basename() work, we can get the base name of a record from the whole index name.

The sentence structure of the capacity is:

os.path.basename(path)

We need to pass the whole pathname into the basename() work as a contention. To start with, we will import the os module.

The result of ‘os.path.basename(directory)’ will be ‘program1.csv’. In this way, we will consider the split capacity and pass the spot character as the separator. That will return a rundown containing [ ‘program1’ , ‘csv’ ]. So we will print the principal thing of that rundown.

1
2
3
import os
directory = '/Users/Programs/Directory/program1.csv'
print(os.path.basename(directory).split('.')[0])

The output will be:

program1

5. Utilizing pathlib.Path.stem() to Get Filename Without Extension in Python

The pathlib module in python is utilized to manage the document ways. At the point when we would rather not get the total way, we can utilize pathlib.Path.stem(). Utilizing the stem property, we will get the record name without its expansion.

For that, first, we should import the pathlib module. Then, at that point, we will pass the ‘catalog’ inside the pathlib.Path() work. Then, at that point, we will utilize the stem property.

1
2
3
4
5
6
import pathlib
directory = '/Users/Programs/Directory/program1.csv'
filename = pathlib.Path(directory).stem
print(filename)

The output filename is:

program1

6. By the rpartition() capacity to Get Filename Without Extension in Python

The rpartition() work parts a given string into three sections. One section will be the separator and the other two sections will be the strings to the left and the right half of the separator.

The syntax of the rpartition() function is:

string.rpartition(separator)
1
2
directory = '/Users/Programs/Directory/program1.csv'
print(directory.rpartition('.')[0])

Output:

/Users/Programs/Directory/program1

Technique 1: Using Python os module splitext() work

Consideration nerd! Reinforce your establishments with the Python Programming Foundation Course and gain proficiency with the fundamentals.

In the first place, your meeting arrangements Enhance your Data Structures ideas with the Python DS Course. Also in the first place your Machine Learning Journey, join the Machine Learning – Basic Level Course

This capacity parts the record way string into document name and record augmentation into a couple of root and expansion with the end goal that when both are added then we can recover the record way once more (file_name + expansion = way). This capacity is liked to utilize when the OS module is being utilized.

Example:

import os
 
 
# this will return a tuple of root and extension
split_tup = os.path.splitext('my_file.txt')
print(split_tup)
 
# extract the file name and extension
file_name = split_tup[0]
file_extension = split_tup[1]
 
print("File Name: ", file_name)
print("File Extension: ", file_extension)

Output:

('my_file', '.txt')
File Name:  my_file
File Extension:  .txt

Method 2: Using Pathlib module

pathlib.Path().suffix method of the Pathlib module can be used to extract the extension of the file path. This method is preferred for an object-oriented approach.

Example:

import pathlib
 
# function to return the file extension
file_extension = pathlib.Path('my_file.txt').suffix
print("File Extension: ", file_extension)

Output:

File Extension:  .txt

Getting File Extension in Python

Java Tricky Program 20 – double subtraction and BigDecimal
import os

# unpacking the tuple
file_name, file_extension = os.path.splitext("/Users/pankaj/abc.txt")

print(file_name)
print(file_extension)

print(os.path.splitext("/Users/pankaj/.bashrc"))
print(os.path.splitext("/Users/pankaj/a.b/image.png"))

Output:

File Extension Python

File Extension in Python

  • In the first example, we are directly unpacking the tuple values to the two variables.
  • Note that the .bashrc file has no extension. The dot is added to the file name to make it a hidden file.
  • In the third example, there is a dot in the directory name.

Get File Extension using Pathlib Module

We can also use pathlib module to get the file extension. This module was introduced in Python 3.4 release.


>>> import pathlib
>>> pathlib.Path("/Users/pankaj/abc.txt").suffix
'.txt'
>>> pathlib.Path("/Users/pankaj/.bashrc").suffix
''
>>> pathlib.Path("/Users/pankaj/.bashrc")
PosixPath('/Users/pankaj/.bashrc')
>>> pathlib.Path("/Users/pankaj/a.b/abc.jpg").suffix
'.jpg'
>>>

Also ReadHow to create a vector in Python using NumPy

Leave a Reply

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