Python os.path.dirname() Method



The Python os.path.dirname() method is used to extract the directory component of a path. It represents the path to the parent directory of the specified file or directory. It essentially returns the head part of the path which excludes the last component (e.g., filename or last directory name).

If the provided path ends with a directory separator (e.g., / on Unix-like systems or \ on Windows), the method returns the path to the parent directory itself, without any further components (i.e. trailing slash).

Syntax

Following is the basic syntax of the Python os.path.dirname() method −

os.path.dirname(path)

Parameter

This method accepts a string as a parameter representing the path from which the directory component will be extracted.

Return Value

The method returns a string representing the directory component extracted from the given path.

Example

In the following example, we are extracting the directory "/home/lenovo/documents" from the file path "/home/lenovo/documents/file.txt" using the dirname() method −

import os
file_path = "/home/lenovo/documents/file.txt"
directory = os.path.dirname(file_path)
print(directory)      

Output

The output obtained is as follows −

/home/lenovo/documents

Example

Here, we are extracting the parent directory from the directory path "/path/to/directory/" using the dirname() method −

import os
dir_path = "/path/to/directory/"
parent_directory = os.path.dirname(dir_path)
print(parent_directory)   

Output

Following is the output of the above code −

/path/to/directory

Example

In this example, we are extracting the directory from the Windows file path "C:\Users\user\Documents\file.txt" using the dirname() method −

import os
file_path = "C:\\Users\\Lenovo\\Documents\\file.txt"
directory = os.path.dirname(file_path)
print(directory)      

Output

The result produced is as shown below −

The directory is: C:\Users\Lenovo\Documents

Example

This example shows that if the path does not contain any directory information, the method returns an empty string −

import os
path = ""
directory = os.path.dirname(path)
print("The directory obtained is:",directory)  

Output

We get the output as shown below −

The directory obtained is:  
os_path_methods.htm
Advertisements