find the parent directory of a directory in python

You can find the parent directory of a directory using the os module in Python. The os.path.dirname() function returns the parent directory of a given path. Here's an example:

main.py
import os

path = "/home/user/Documents/myproject/"
parent_dir = os.path.dirname(path)

print(parent_dir)
106 chars
7 lines

Output:

main.py
/home/user/Documents/
22 chars
2 lines

In this example, the os.path.dirname() function returns the parent directory of the myproject directory. The result is assigned to the parent_dir variable which is then printed to the console.

gistlibby LogSnag