如何获取Python中的父目录名称?

How to get the name of parent directory in Python?

我在 python 中有一个程序可以打印出关于文件系统的信息...我需要知道将父目录的名称保存到一个变量...

例如,如果文件系统的一小部分看起来像这样:
父目录
子目录
子目录
如果我在 ChildDirectory 中,我需要将名称 ParentDirectory 保存到某个字符串...这里是一些 伪代码
import os
var = os.path.parent()
print var
附带一提,我使用的是 Python 2.7.6,因此我需要与 2.7.6 兼容...

您可以使用 __file__ 变量获取脚本驻留的完整文件路径,然后您可以使用 os.path.abspath() 获取文件的绝对路径,然后使用 os.path.join()连同您的当前路径,以及大多数操作系统中的父目录描述符 - ..,但您可以使用 os.pardir(从 python 获取它,以便它真正独立于平台)然后再次获取其绝对路径获取当前目录的完整路径,然后再次使用它以相同的逻辑获取其父目录。

示例代码 -

import os,os.path
curfilePath = os.path.abspath(__file__)

# this will return current directory in which python file resides.
curDir = os.path.abspath(os.path.join(curfilePath, os.pardir))

# this will return parent directory.
parentDir = os.path.abspath(os.path.join(curDir, os.pardir))