【问题标题】:How to get the name of parent directory in Python? [duplicate]如何在 Python 中获取父目录的名称? [复制]
【发布时间】:2015-06-21 18:29:02
【问题描述】:

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

例如,如果文件系统的一小部分如下所示:
ParentDirectory
ChildDirectory
SubDirectory
如果我在 ChildDirectory 中,我需要将名称 ParentDirectory 保存到某个字符串...这里是一些 伪代码
import os
var = os.path.parent()
print var
附带说明一下,我使用的是 Python 2.7.6,所以我需要与 2.7.6 兼容...

【问题讨论】:

  • 因为我认为“这个问题没有显示任何研究工作”的反对描述很合适。

标签: python variables directory


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 2019-12-17
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多