3 Examples to use Python os.path.basename method

Table of Contents

The Python os.path.basename method is used to extract the base name of a pathname. This is useful when you want to process only the filename or directory name from a full pathname.

Understanding os.path.basename method

This method internally use os.path.split() method to split the specified path into a pair (head, tail). os.path.basename() method returns the tail part after splitting the specified path into (head, tail) pair.

os.path.basename Syntax

Syntax: os.path.basename(path)


  • path: A path-like object representing a file system path.
  • Return Type: This method returns a string value which represents the base name the specified path.


3 Examples of os.path.basename method in Python

Here are three more examples of the os.path.basename method in action:

>>> os.path.basename(‘C/foo/bar/baz.txt’)
>>> os.path.basename(‘/etc/passwd’)
>>> os.path.basename(‘/etc/telegraf/telegraf.conf’)

Python os.path.dirname vs Python os.path.basename

os.path.dirname is the inverse of os.path.basename – it returns the directory name portion of a pathname. For example,

>> os.path.dirname(‘/etc/telegraf/telegraf.conf’)

Are there any other methods related to os.path.basename that I should know about?

There are several other useful methods related to pathnames that you should be aware of:

  • os.path.split() splits a full pathname into its individual filename and directory name components
  • os.path.join() combines multiple pathname components


For example:

>>> os.path.split(‘/etc/telegraf/telegraf.conf’)
(‘/etc/telegraf’, ‘telegraf.conf’)
>>> print(os.path.join(“/etc”, “telegraf”,”telegraf.conf”))



Welcome to!

Our website is dedicated to providing comprehensive information on using Linux.

We hope you find our site helpful and informative, and we welcome your feedback and suggestions for future content.

Learn More