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

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

and

C:\ ---> C:\

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


当前回答

如果你只想要作为参数提供的文件的直接父文件夹的名称,而不是该文件的绝对路径:

os . path . split (os . path dirname (currentDir)) [1]

例如,currentDir值为/home/user/path/to/myfile/file.ext

上面的命令将返回:

我的文件

其他回答

获取父目录路径并创建新目录(名称为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 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 "------------------------------------------------------------"

上面给出的答案对于上升到一个或两个目录级别都非常合适,但是如果需要遍历目录树的许多级别(例如,5或10级),它们可能会有点麻烦。这可以通过加入一个N个os的列表来简单地完成。os.path.join中的Pardirs。例子:

import os
# Create list of ".." times 5
upup = [os.pardir]*5
# Extract list as arguments of join()
go_upup = os.path.join(*upup)
# Get abspath for current file
up_dir = os.path.abspath(os.path.join(__file__, go_upup))

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

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

os.path.split(os.path.abspath(mydir))[0]