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

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

and

C:\ ---> C:\

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


当前回答

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

其他回答

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', '..'))

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

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));
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
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 "------------------------------------------------------------"
print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))

您可以使用它来获取py文件当前位置的父目录。