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

问题描述:

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

例如,如果一小部分文件系统是这样的:
ParentDirectory
ChildDirectory
子目录
如果我是ChildDirectory内的,我需要保存名称ParentDirectory一定串......这里是一些伪代码
import os
var = os.path.parent()
print var
在一个侧面说明,我使用Python 2.7.6,所以我需要与2.7.6兼容...

+0

为什么向下票呢? –

+0

因为我认为downvote描述“这个问题没有显示任何研究工作”适合。 – TessellatingHeckler

您可以使用__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)) 
+0

非常感谢你 –

+0

不客气。 –