The Python dirname() function is very useful for getting the directory name of a given path.
import os
print(os.path.dirname("/Home/Documents/example.py")
#Output:
/Home/Documents
When working with file systems, it can be useful to be able to get the directory name and path of a file.
The Python os module provides us with a number of great functions to be able to perform many operating system tasks.
With the os module, we can easily get the directory name of a path.
To get the directory name of a path, we can use the os.path.dirname() function.
Pass a string representing the path of a file, and you will get the full path of the directory of that file.
Below is an example of how to use the Python dirname() function to get the directory name of a file.
import os
print(os.path.dirname("/Home/Documents/example.py")
#Output:
/Home/Documents
Hopefully this article has been useful for you to learn how to get the directory name of a path using the Python dirname() function.