VOOZH about

URL: https://www.geeksforgeeks.org/python/python-os-path-dirname-method/

⇱ Python | os.path.dirname() method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | os.path.dirname() method

Last Updated : 12 Dec, 2025

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.


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.


Output
/home/user

Example 2: This example extracts the parent directory that contains a specific file.


Output
/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.

Comment