Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the parent directory in Python?

Tags:

python

Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g.

C:\Program Files ---> C:\ 

and

C:\ ---> C:\ 

If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google.

like image 408
Mridang Agarwalla Avatar asked May 18 '10 18:05

Mridang Agarwalla


People also ask

How do I find my home directory in Python?

expanduser('~') to get the home directory in Python. This also works if it is a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. This function is recommended because it works on both Unix and Windows.


1 Answers

Python 3.4

Use the pathlib module.

from pathlib import Path path = Path("/here/your/path/file.txt") print(path.parent.absolute()) 

Old answer

Try this:

import os print os.path.abspath(os.path.join(yourpath, os.pardir)) 

where yourpath is the path you want the parent for.

like image 50
kender Avatar answered Oct 12 '22 02:10

kender