Python | os.path.dirname() method
os.path.dirname() is a path-handling function in Python that extracts the directory portion of a given file system path. It helps you separate the directory from the filename or locate where a file or folder exists inside the system. This function is part of the os.path module, which provides utilities for manipulating file paths.
Example: This example extracts the directory name from a basic file path.
import os.path
p = "/home/user/docs/file.txt"
res = os.path.dirname(p)
print(res)
Output
/home/user/docs
Explanation: os.path.dirname(p) removes the last component (file.txt) and returns the directory path.
Syntax
os.path.dirname(path)
Parameter: path - a path-like string from which the directory name must be extracted.
Example
Example 1: This example extracts the parent directory that contains a specific folder.
import os.path
p = "/home/user/projects"
res = os.path.dirname(p)
print(res)
Output
/home/user
Example 2: This example extracts the parent directory that contains a specific file.
import os.path
p = "/home/user/docs/report.pdf"
res = os.path.dirname(p)
print(res)
Output
/home/user/docs
Example 3: This example shows if the input contains only a filename, no directory will be extracted.
import os.path
p = "notes.txt"
res = os.path.dirname(p)
print(res)
Explanation: os.path.dirname(p) returns an empty string because the path has no directory component.