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.
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.
Use the pathlib
module.
from pathlib import Path path = Path("/here/your/path/file.txt") print(path.parent.absolute())
Try this:
import os print os.path.abspath(os.path.join(yourpath, os.pardir))
where yourpath
is the path you want the parent for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With