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

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

and

C:\ ---> C:\

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


当前回答

只是在Tung的答案中添加了一些东西(如果你在unix机器上,你需要使用rstrip('/')来更安全)。

>>> input1 = "../data/replies/"
>>> os.path.dirname(input1.rstrip('/'))
'../data'
>>> input1 = "../data/replies"
>>> os.path.dirname(input1.rstrip('/'))
'../data'

但是,如果你不使用rstrip('/'),给定你的输入是

>>> input1 = "../data/replies/"

将输出,

>>> os.path.dirname(input1)
'../data/replies'

这可能不是你所看到的,因为你想要两者。/data/replies/" and "../data/回复“以同样的方式表现。

其他回答

import os 

def parent_directory():
  # Create a relative path to the parent of the current working directory 
  relative_parent = os.path.join(os.getcwd(), "..") # .. means parent directory

  # Return the absolute path of the parent directory
  return os.path.abspath(relative_parent)

print(parent_directory())
import os.path

os.path.abspath(os.pardir)
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', '..'))
os.path.split(os.path.abspath(mydir))[0]

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

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