How to get the file names without extension in Python

Hey coder! today, in this article let us learn how to get the file names without extension in Python.
There are many ways where we can get the file names without the extension.

  • By using pathlib.Path.stem() function.
  • Using rsplit() function.
  • Using os.path.splitext() function.
  • By using rpartition() function. All the above-mentioned ways are equally important. Let us go through them one by one.

Using pathlib.Path.stem() function

For this process, firstly we need to import the pathlib module and then we can use the stem() property from it.
So that we will get the file without any extension.

Example Code:

from pathlib import Path
 
dir = 'https://cdn.codespeedy.com/path/to/some/file.txt'
print(Path(dir).stem)

Basically, the stem property is used to create the stem plots and it is also used for getting the files without any extension.

Output

/path/to/some/file

 

Using rsplit() function

We can use the rsplit() function to get the file name without extension in Python.

Example Code:

dir = 'https://cdn.codespeedy.com/path/to/some/file.txt'
print(dir.rsplit('.', 1)[0])

In the above code by using the rsplit() function we will exclude the extension in the given “dir”.

Output

path/to/some/file

 

Using os.path.splitext() function

For this function we need to import the os module.

Moreover, in os.path.splitext() function, we need to pass the “path” as the argument, where path is divided into (root,ext).

This pair will help us in extracting the file name without extension.

Example Code:

import os
 
dir = 'https://cdn.codespeedy.com/path/to/some/file.txt'
print(os.path.splitext(dir)[0])

Output

     path/to/some/file

 

By using rpartition() function

Basically, the rpartition() function will split the string into 3 parts, two of them are strings and the other one is seperator.

At first, let us go through through the example code.

Example Code:

dir = 'https://cdn.codespeedy.com/Users/Programs/Directory/program1.csv'
print(directory.rpartition('.')[0])

Output

/Users/Programs/Directory/program1

Finally, this is the end of our interesting article.
The links provided below are in your interest

Leave a Reply

Your email address will not be published.