HOWTO · Python
How to Get Parent Directory in Python
This tutorial demonstrates how to get parent directory of a path in Python
On this page
This tutorial will explain various methods to get the parent directory of a path in Python. The parent directory is the directory directly above the given directory or file. For example, the parent directory of a path C:\folder\subfolder\myfile.txt is C:\folder\subfolder. Every directory except the root has a distinct parent; the parent of the root directory is the root itself.
Get a Path’s Parent with Path.parent
The pathlib module represents a path as a Path object. Its parent property gives the logical parent of the path, as another Path object; wrap it in str() if you need the parent as a string. There is nothing to call and no argument to pass: you read the property from the Path you constructed.
The example code below demonstrates how to use the parent property to get the parent directory of a path in Python:
from pathlib import Path
path1 = Path(r"C:\folder\subfolder\myfile.txt")
path2 = Path(r"C:\Myfile.txt")
print(path1.parent)
print(path2.parent)
Output:
C:\folder\subfolder
C:\
Use os.pardir with os.path.join()
os.pardir is a constant string that refers to the parent directory. It is '..' on Windows and on POSIX systems, including macOS.
When we combine the given path and os.pardir with the os.path.join() function and normalize the result with os.path.abspath(), we get the parent directory of the given path.
The example code below demonstrates how to use os.pardir and os.path.join() to get the parent directory of a path:
import os.path
path1 = r"C:\folder\subfolder\myfile.txt"
path2 = r"C:\Myfile.txt"
print(os.path.abspath(os.path.join(path1, os.pardir)))
print(os.path.abspath(os.path.join(path2, os.pardir)))
Output:
C:\folder\subfolder
C:\
As mentioned above, we could also get the same result if we replace os.pardir with '..'.
import os.path
path1 = r"C:\folder\subfolder\myfile.txt"
path2 = r"C:\Myfile.txt"
print(os.path.abspath(os.path.join(path1, "..")))
print(os.path.abspath(os.path.join(path2, "..")))
Output:
C:\folder\subfolder
C:\
Get a Path’s Parent with os.path.dirname()
os.path.dirname() is a function that takes a path string as input and returns the directory part of the path: everything up to the final path separator. For a path that points to a file, that directory part is the parent directory, returned as a string.
The example code below demonstrates how to use os.path.dirname() to get the parent directory of a path:
import os.path
path1 = r"C:\folder\subfolder\myfile.txt"
path2 = r"C:\Myfile.txt"
print(os.path.dirname(path1))
print(os.path.dirname(path2))
Output:
C:\folder\subfolder
C:\