![]() |
VOOZH | about |
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.
/home/user/docs
Explanation: os.path.dirname(p) removes the last component (file.txt) and returns the directory path.
os.path.dirname(path)
Parameter: path - a path-like string from which the directory name must be extracted.
Example 1: This example extracts the parent directory that contains a specific folder.
/home/user
Example 2: This example extracts the parent directory that contains a specific file.
/home/user/docs
Example 3: This example shows if the input contains only a filename, no directory will be extracted.
Explanation: os.path.dirname(p) returns an empty string because the path has no directory component.