Python os.path.basename: Complete Guide

Working with UNIX or MacOS uses the slash / as path separator, and Windows uses the backslash \ as the separator. The separator in the OS running Python can be checked and confirmed by the os.path.sep() function. Let’s see how os.path.basename() function works in Python.

Python os.path.basename

The os.path.basename() is a built-in Python method used to get the base name in the specified path. The path.basename() function takes an argument of a specified path and returns the base name of the pathname path.

To extract the file name from the path in Python, use the os.path.basename() method.

Syntax

os.path.basename(path)

Parameters

The basename() function takes a path-like object representing a file system path.

Return Value

The path.basename() method returns a string value representing the base name of the specified path.

Example

To work with the OS module in Python, import the os module at the start of the file and use the path.basename() function.

import os

path = '/Users/krunal/Desktop/code'

basename = os.path.basename(path)

print(basename)

Output

code

As you can see from the output, that os.path.basename() method internally use os.path.split() function to split the specified path into a pair called head and tail. The os.path.basename() function returns the tail part of the path.

In our example, the tail part of the path is the code directory which is why it returns the code in the output.

Extract the file name using os.path.basename()

To extract the file name from the path in Python, use the os.path.basename() method.

import os

path = '/Users/krunal/Desktop/code/python/database/app.py'

basename = os.path.basename(path)

print(basename)

Output

app.py

And we get the filename from the path using the basename() function.

Difference between os.path.dirname and os.path.basename()

The os.path.dirname(path) function in Python returns the head of the path in.

The os.path.basename(path) function returns the tail of the path in Python.

These functions are used when you get the filename/directory name given a full pathname.

Use os.path.split() to get both the file name and the directory name (folder name).

The os.path.split() function returns the tuple of file name returned by os.path.basename() and directory name returned by os.path.dirname().

See also

Python os.path.abspath()

Python os.path.exists()

Python os.path.join()

Python os.listdir()

Python os.system()

Leave a Comment

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