有人能告诉我如何在Python中跨平台获取路径的父目录吗?如。

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

and

C:\ ---> C:\

如果目录没有父目录,则返回目录本身。这个问题似乎很简单,但我无法从谷歌中找到它。


当前回答

import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"

其他回答

import os

dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))

查找当前工作目录的父目录。

import pathlib
pathlib.Path().resolve().parent

Python 3.4

使用pathlib模块。

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

旧的答案

试试这个:

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

你的路径就是你想要父路径的路径。

假设我们有这样的目录结构

1]

/home/User/P/Q/R

我们想要从目录R中访问“P”的路径,然后我们可以访问using

ROOT = os.path.abspath(os.path.join("..", os.pardir));

2]

/home/User/P/Q/R

我们想要从目录R中访问“Q”目录的路径,然后我们可以访问using

ROOT = os.path.abspath(os.path.join(".", os.pardir));
os.path.split(os.path.abspath(mydir))[0]