Get filename without extension from a path in Python

In this article, we will learn to extract the filename from a give file without the extension of the file.

Table Of Contents

A Pathname consists of name of the file, location at which the file is stored and the extension of the file. In order to extract filename we have to separate the filename from both extension and path. Now we will look into various methods through which we can perform this task.

Using rfind() method :

The method which we will be using in this technique is rfind(). This is a built in python string method which returns the last occurrence of the given value in string. If not found, then it returns -1.

It receives three parameter :

  • value: The element which needs to be find
  • Start Position : The position from which we need to check in the given string. Default position is 0.
  • End Position : The position till where we need to check. Default position is -1 i.e. the end of string.

It returns the highest index of substring in string. If the substring does not exist, then it returns -1.

SYNTAX :

string.rfind(value, start, end)

EXAMPLE :

file_name = '/example.txt'

index = file_name.rfind(".")

print("name of the file without extension is :", file_name[1:index])

OUTPUT :

name of the file without extension is : example

In the code above, we have stored filename in a variable file_name. We searched for the last index position of . (dot) in string, because there is always a dot between name and extension of a file. Next we have printed filename from index 1 to index where dot has been found. Also if we use 0th index we shall get the filename something like this :

CODE :

file_name = '/example.txt'

index = file_name.rfind(".")

print("name of the file without extension is :",file_name[:index])

OUTPUT :

name of the file without extension is : /example

Using splitext() method:

This method comes from the os module, which comes bundled in Python. The splitext() splits the path in two parts : root and extension. It takes pathname as an argument and returns extension and root in tuple.

SYNTAX :

import os
os.path.splitext(path)

EXAMPLE :

import os

file_path = '/example.txt'

# Get path and extension of file
path , ext = os.path.splitext(file_path)

print("Path of the file :" ,path)
print("Extension of the file :",ext)

# Get file name by spitting the path
file_name = path.split('/')

print("File name without extension: " , file_name[-1])

OUTPUT :

Path of the file : /example
Extension of the file : .txt
File name without extension:  example

In code above, you can see file_path variable has path of the file. Path and Extension of the file has been extracted through os.path.splitext() in path and ext variables respectively. Then split the file_name with ‘/’. It will return a list of all folders and filename without extension. Select the last value from this list, because that will be our filename without extension.

Using the split() method:

Another method that we can use is the split() method. Unlike splitext() method we don’t need to import os module for it, but we need to use split() function twice. First we will split the path from “.” and after that we will split from ‘/’ using the split() function. Look at the example below.

EXAMPLE :

file_path = '/example.txt'

path_contents = file_path.split('.')

# print the separated filename and extension
print(path_contents) 

# get filename without extension
file_name = path_contents[0].split('/')[-1]

print(file_name)

OUTPUT :

['/example', 'txt']
example

Here we have the filepath stored in file_path variable. Then we used the split() method with the separator ‘.’ to split filepath and extension.Again split() method has been used with separator ‘/’ to split filename from filepath.

Using Basename() method :

Next method through which we can remove extension from a given path is Basename() function. This function of the os module is used to extract filename from a given path. It recieves only one parameter which is a filepath. It returns a string which is basename i.e. filename without extension

SYNTAX :

os.path.basename(path) 

To get the filename without the extension from a path, we will use basename() function with split() function. We will provide pathname as a parameter in basename() function and “.” as a separator param in split() function. See the code below.

EXAMPLE :

import os 
path_name = '/example.txt'

# Print filename without extension 
print(os.path.basename(path_name).split('.')[0])

OUTPUT :

example

In code above , filename has been extracted from a given path using the basename() function and split() functions.

Using pathlib.Path.stem() method :

This built method of python is used to handle paths. The stem property of pathlib is used to get the filename without its extension.

SYNATX :

import pathlib
pathlib.Path(path).stem

To remove extension from a given path, first we will import pathlib module and then we will pass the path inside pathlib.Path() function. Then we will use the stem function to remove extension from the filename. See the code below :

EXAMPLE :

import pathlib

path_name = '/example.txt'
file_name = pathlib.Path(path_name)

# Print file_name with extension.
print(file_name)

# Remove extension from filename using stem &
# Print file_name without extension
print(file_name.stem)

OUTPUT :

\example.txt
example

As you can see, the pathlib.Path.stem has been used to remove extension from a filename.

Summary

We learned about the five different methods to separate filename from extension. You can use any of the methods depending on your need. Try to run and understand the codes above in your machine. Here we have used Python 3.10.1 for writing example codes. To check your version write python –version in your terminal.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top