从Python脚本获取当前目录的父级

Fed*_*ina 36 python sys sys.path

我想从Python脚本中获取当前目录的父级.例如,我/home/kristina/desire-directory/scripts在这种情况下从欲望路径启动脚本/home/kristina/desire-directory

我知道sys.path[0]sys.但我不想解析sys.path[0]结果字符串.有没有其他方法可以在Python中获取当前目录的父级?

vau*_*tah 81

使用os.path

获取包含脚本的目录的父目录(无论当前工作目录如何),您需要使用__file__.

在脚本里面os.path.abspath(__file__)用来获取脚本的绝对路径,并调用os.path.dirname两次:

from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Run Code Online (Sandbox Code Playgroud)

基本上,您可以os.path.dirname根据需要多次调用来遍历目录树.例:

In [4]: from os.path import dirname

In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'

In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
Run Code Online (Sandbox Code Playgroud)

如果要获取当前工作目录的父目录,请使用os.getcwd:

import os
d = os.path.dirname(os.getcwd())
Run Code Online (Sandbox Code Playgroud)

使用pathlib

您也可以使用该pathlib模块(Python 3.4或更高版本).

每个pathlib.Path实例都具有parent引用父目录的parents属性,以及属性,该属性是路径的祖先列表.Path.resolve可用于获得绝对路径.它还解析了所有符号链接,但Path.absolute如果不是所需的行为,您可以使用它.

Path(__file__)并分别Path()表示脚本路径和当前工作目录,因此为了获取脚本目录的父目录(不管当前工作目录),您将使用

from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
Run Code Online (Sandbox Code Playgroud)

获取当前工作目录的父目录

from pathlib import Path
d = Path().resolve().parent
Run Code Online (Sandbox Code Playgroud)

请注意,这d是一个Path实例,并不总是很方便.您可以str在需要时轻松将其转换为:

In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
Run Code Online (Sandbox Code Playgroud)


aka*_*hbw 7

这对我有用(我在Ubuntu上):

import os
os.path.dirname(os.getcwd())
Run Code Online (Sandbox Code Playgroud)


Gav*_*hen 7

Path.parentpathlib模块中使用:

from pathlib import Path

# ...

Path(__file__).parent
Run Code Online (Sandbox Code Playgroud)

您可以使用多个调用来parent进一步进行以下操作:

Path(__file__).parent.parent
Run Code Online (Sandbox Code Playgroud)


cor*_*vid 6

import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
Run Code Online (Sandbox Code Playgroud)