Int*_*... 3 python directory variables
我在python中有一个程序打印出有关文件系统的信息......我需要知道将父目录的名称保存到变量中...
例如,如果文件系统的一小部分看起来像这样:
ParentDirectory
ChildDirectory
SubDirectory
如果我在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))
Run Code Online (Sandbox Code Playgroud)