Master Python Basename With These 5 Examples

File handling is a significant aspect of every programming language. Whether be a pro developer or a newbie, we still are unaware of powerful methods or functions which are available in default libraries. Each of these libraries is made with the utmost intention to provide a better file handling interface. The python OS module has tons of functions like basename which can help you drastically to create nonspaghetti and secured codes.

Python basename() is a function included in the OS module. This function accepts a string parameter to be the path of the file and it returns the base file name of that specific path. Normally, many programmers split the path and use the final split to get a file path and something like this. But this method completely eliminates any manual intervention.

In this post, we’ll go through the syntax, parameters, returns, and use cases of the Python Basename function.

Syntax of Python Basename

The syntax of the basename function is –

os.path.basename(path)

Here, the path is expected to be a string, bytes, or os.Pathlike and it should be a valid path. For example, you cannot have a random path string that isn’t a valid path.

Returns

It returns a string with a basename of the file or directory of the path passed. For files, it’s the file name along with its extension, and for directories, it’s the folder name.

Importing Module

OS module is already included in built-in modules of Python. This means you don’t have to install any other module or library in order to use the python basename function. Simply, use the –

import os

and use the function as os.path.basename()

This will take care of all the imports and make sure that you have included the function module beforehand.

Examples of Python Basename

There are many use cases of basename function. We’ll have a look at all of them –

1. Directory Name

In the following example, we’ll use only the directory name as a parameter in the basename functions.

Code –

import os

path = "pythonpool/folder1"
x = os.path.basename(path)
print(x)

Output –

folder1

Explanation –

In the above example, we first imported the os module to include the basename function. Then we created a dummy path variable that has pythonpool/folder1 as a pathname. We’ll use this as a parameter for the basename function. As you can check that output is folder1, it only returns the basename excluding the previous path.

2. File Name

In the following example, we’ll use only the file name as a parameter in the basename functions.

Code –

import os

path = "pythonpool/file.txt"
x = os.path.basename(path)
print(x)

Output –

file.txt

Explanation –

After importing the os module, we can use the os.path.basename function. This time, we’ll pass a file path as an argument to the function. Since basename returns the basename of file or folder, you can verify that the output, in this case, was file.txt.

3. Full Path

In the following example, we’ll use the full path as a parameter in the python basename functions.

Code –

import os

path = "/media/usr/pythonpool/file.txt"
x = os.path.basename(path)
print(x)

Output –

file.txt

Explanation –

In the above example, we initialized the path to be the full path for file file.txt. Unlike the relative path, this path contains all the parent directories. But still, the output, in this case, is the same, file.txt. This ensures that the python basename works on the full path as well.

4. Invalid Path

Now we’ll test the function with an invalid path. We’re going to use invalid objects which are not allowed to as parameters for the function.

Code –

import os

path = 1
x = os.path.basename(path)
print(x)

Output –

TypeError: expected str, bytes or os.PathLike object, not int

Explanation –

In this case, we’ve used integer 1 as a parameter for the function. This integer is not a valid path nor a valid argument for the function. As a result, the function threw an error stating it’s expecting a string, bytes, or os.Pathlike object.

You can handle such cases by using Try Except for blocks and take care if any invalid argument is passed into the basename function.

What is the Difference between Python Basename and Dirname?

Those who’ve been using the OS module for a long time should know the dirname function. But how is it different than basename? We’ll check it how –

Basename refers to the base name of the file or directory ignoring the parent directories in the path. Whereas the dirname refers to the parent directories in the path ignoring the base name. As a result, a complete path can be broken down into this formula –

PATH = DIRNAME + BASENAME

Python basename vs dirname

Both the functions use the string split method and will be consistent results if you use both in coordination. Let’s have a look with an example –

Code –

import os

path = "/media/usr/pythonpool/file.txt"
x = os.path.basename(path)
y = os.path.dirname(path)
print(y, x)

Output –

/media/usr/pythonpool file.txt

Explanation –

Here, we used both basename and dirname on the same path. As you can verify in the output, the basename returns the filename and for dirname, it returns the directory path.

How to Get Python Basename without Extension?

You can simply split the basename string and fetch the slice of the split string excluding the last split. This will result in a filename without an extension variable. The following example will help you to understand –

Code –

import os

path = "/media/usr/pythonpool/file.min.txt"
x = os.path.basename(path)

# without extension
if "." in path:
    x = ".".join(x.split(".")[:-1])
print(x)

Output –

file.min

Explanation –

Here we first split the basename by character “.”. This will create a list of all the splits. Now we can slice it by using [:-1] and removing the extension part.

But our output still exists in list format. As a result, we’ll use the join() method to join the list to string.

This will help you remove the extension of the filename got from the basename.

FAQs on Python Basename

Is the basename function the same as that of the basename command in Linux?

Yes, it works exactly the same. You get the tail of the path in both the function/commands.

Does the Python basename function works for URLs?

Yes, the basename function works on the URLs as well. It will return the basename of the URL passed. For example, if you’re URL is import os https://www.pythonpool.com/file.txt then you’ll have a return value of file.txt

Does basename exist in the pathlib module?

No, basename doesn’t exist exactly as basename alias. But you can use the alternative of PurePath.name from the pathlib module to get the basename.

Final Words

Python basename is a powerful function that can be used directly to get the base name of the path’s folder name or filename. Moreover, you can combine it with dirpath and work with the full path system. The above examples demonstrated every use case possible for the function.

If you have any doubts, please let us know in the comments.

References

Python Official Docs. OS Path module. docs.python.org.
Python Official Docs. Purepath.name attribute. docs.python.org.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments