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”))



David Cao
David Cao

Hey there! I am David, a Cloud & DevOps Enthusiast and 18 years of experience as a Linux engineer. I work with AWS, Git & GitHub, Linux, Python, Ansible, and Bash. I am a technical blogger and a Software Engineer, enjoy sharing my learning and contributing to open-source.