Latest Code Tutorials

Python os.path.dirname: The Complete Guide

The OS module provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. Working with UNIX or MacOS uses the slash / as path separator, and Windows uses the backslash \ as the separator. The separator in the OS running Python can be checked and confirmed by the os.path.sep() function.

Python os.path.dirname

The os.path.dirname() is a built-in Python function that returns the directory name of the pathname path. This is the first element of the pair returned by passing a path to the function split().

To extract the file name from the path in Python, use the os.path.basename() method.

To extract the head folder from the path in Python, use the os.path.dirname() method.




The os.path.dirname() function accepts the path-like object representing a file system path.

Return Value

The os.path.dirname() function returns the string value representing the directory name from the specified path.


To work with the OS module in Python, import the os module at the start of the file and use the path.dirname() function.

import os

path = '/Users/krunal/Desktop/code/python/database/'

dirname = os.path.dirname(path)




As you can see from the output, that os.path.dirname() method internally use os.path.split() function to split the specified path into a pair called head and tail.

The os.path.dirname() function returns the head part of the path. The os.path.dirname() function returns all path components, excluding the last one.

That is it for this article.

See also

Python os.path.abspath()

Python os.path.exists()

Python os.path.join()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.