How to get the directory name of a given path in Python

How to get the directory name of a given path in Python:

In this post, we will learn how to get the directory name of a given path in python. We will use dirname() method of os.path submodule for that.

os.path is a submodule of the os module. os module contains different methods related to the operating system. os.path is a submodule in os. This submodule includes different important functions of file paths. Since os is an inbuilt method, we can use it directly without need to install any other third party library.

os.path.dirname() method can be used to get the directory name of a given path.

Python os.path.dirname() definition:

os.path.dirname() is defined as below:

os.path.dirname(path)

We need to import os module to use this method. This method takes the path, which is the given path. It returns the directory name of this path.

Starting from python 3.6, it can also take a path-like object.

Example of os.path.dirname():

Let’s take a look at one example on how to use os.path.dirname:

import os

print(os.path.dirname("C:\\Users\\cvc\\Desktop"))
print(os.path.dirname("C:\\Users\\cvc\\Desktop\\"))
print(os.path.dirname("C:\\Users\\cvc\\Desktop\\file.txt"))

Here, we are using os.path.dirname with three different paths. If you run the above program, it will print the below output:

C:\Users\cvc
C:\Users\cvc\Desktop
C:\Users\cvc\Desktop

You might also like: