Python os.path.basename() Method

Python os.path.basename() method is used to extract the base name of a pathname, which is the last component of the path.

Essentially, it returns the tail of the path: the part after the last slash (/) in Unix/Linux or backslash (\) in Windows

This method doesn’t check if the path or file exists; it merely processes the string.

This method is cross-platform and automatically handles differences in path naming conventions between operating systems.

Syntax

os.path.basename(path)

Parameters

Name Description
path (string) It takes a path-like object representing a file system path.

Return Value

It returns a string value representing the base name of the specified path.

Example 1: Basic usage

Visual Representation of Python os.path.basename() Method

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/new.txt'

filename = os.path.basename(path)

print(filename)

Output

new.txt

Example 2: Extracting a directory name as a base name

Extracting a directory name as a base name

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env'

dirname = os.path.basename(path)

print(dirname)

Output

env

Example 3: Base Name of a Windows Path

Base Name of a Windows Path

import os

path = 'C:\\Users\\krunal\\new.txt'

filename = os.path.basename(path)

print(filename)

Output

new.txt

That’s it.

Leave a Comment

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