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

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

and

C:\ ---> C:\

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


当前回答

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))

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

其他回答

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 "------------------------------------------------------------"
os.path.abspath(os.path.join(somepath, '..'))

观察:

import posixpath
import ntpath

print ntpath.abspath(ntpath.join('C:\\', '..'))
print ntpath.abspath(ntpath.join('C:\\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))

Pathlib方法(Python 3.4+)

from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object

传统方法

import os.path
os.path.dirname('C:\Program Files')
# Returns a string

我应该用哪种方法?

如果出现以下情况,请使用传统方法:

如果要使用Pathlib对象,您会担心现有代码生成错误。(因为Pathlib对象不能与字符串连接。) 您的Python版本低于3.4。 你需要一个字符串,你收到了一个字符串。例如,你有一个表示文件路径的字符串,你想要得到父目录,这样你就可以把它放在一个JSON字符串中。转换为Pathlib对象然后再转换回来是很愚蠢的。

如果以上都不适用,请使用Pathlib。


什么是Pathlib?

如果你不知道Pathlib是什么,Pathlib模块是一个很棒的模块,它可以让你更容易地处理文件。大多数(如果不是全部的话)内建的处理文件的Python模块将同时接受Pathlib对象和字符串。我在下面突出了几个来自Pathlib文档的例子,这些例子展示了你可以用Pathlib做的一些漂亮的事情。

在目录树中导航:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

查询路径属性。

>>> q.exists()
True
>>> q.is_dir()
False

获取父目录路径并创建新目录(名称为new_dir)

获取父目录路径

os.path.abspath('..')
os.pardir

示例1

import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))

示例2

import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))

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

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