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

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

and

C:\ ---> C:\

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


当前回答

print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))

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

其他回答

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

@kender的另一个解决方案

import os
os.path.dirname(os.path.normpath(yourpath))

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

但这个解决方案并不完美,因为它不能处理路径为空字符串或点的情况。

另一个解决方案将更好地处理这种极端情况:

import os
os.path.normpath(os.path.join(yourpath, os.pardir))

这里是可以找到的每个情况的输出(输入路径是相对的):

os.path.dirname(os.path.normpath('a/b/'))          => 'a'
os.path.normpath(os.path.join('a/b/', os.pardir))  => 'a'

os.path.dirname(os.path.normpath('a/b'))           => 'a'
os.path.normpath(os.path.join('a/b', os.pardir))   => 'a'

os.path.dirname(os.path.normpath('a/'))            => ''
os.path.normpath(os.path.join('a/', os.pardir))    => '.'

os.path.dirname(os.path.normpath('a'))             => ''
os.path.normpath(os.path.join('a', os.pardir))     => '.'

os.path.dirname(os.path.normpath('.'))             => ''
os.path.normpath(os.path.join('.', os.pardir))     => '..'

os.path.dirname(os.path.normpath(''))              => ''
os.path.normpath(os.path.join('', os.pardir))      => '..'

os.path.dirname(os.path.normpath('..'))            => ''
os.path.normpath(os.path.join('..', os.pardir))    => '../..'

输入路径为绝对路径(Linux路径):

os.path.dirname(os.path.normpath('/a/b'))          => '/a'
os.path.normpath(os.path.join('/a/b', os.pardir))  => '/a'

os.path.dirname(os.path.normpath('/a'))            => '/'
os.path.normpath(os.path.join('/a', os.pardir))    => '/'

os.path.dirname(os.path.normpath('/'))             => '/'
os.path.normpath(os.path.join('/', os.pardir))     => '/'
>>> import os
>>> os.path.basename(os.path.dirname(<your_path>))

例如在Ubuntu中:

>>> my_path = '/home/user/documents'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'user'

例如在Windows中:

>>> my_path = 'C:\WINDOWS\system32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'

这两个例子都是在Python 2.7中尝试的

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