我想从Python脚本中获取当前目录的父目录。例如,我从/home/kristina/desire-directory/scripts启动脚本,本例中的愿望路径是/home/kristina/desire-directory
我认识sys.path[0]在sys。但是我不想解析sys.path[0]结果字符串。在Python中还有其他方法来获取当前目录的父目录吗?
发布于 2015-05-13 15:08:45
使用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基本上,您可以根据需要多次调用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'如果要获取当前工作目录的父目录,请使用os.getcwd
import os
d = os.path.dirname(os.getcwd())使用路径库
您还可以使用pathlib模块(可以在Python3.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')并获取当前工作目录的父目录。
from pathlib import Path
d = Path().resolve().parent注意,d是一个Path实例,并不总是很方便。您可以在需要时轻松地将其转换为str:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'发布于 2016-09-21 13:33:49
使用来自Path.parent模块的pathlib:
from pathlib import Path
# ...
Path(__file__).parent您可以使用对parent的多个调用来进一步推进路径:
Path(__file__).parent.parent发布于 2016-04-29 13:10:57
这对我有用(我在Ubuntu上):
import os
os.path.dirname(os.getcwd())https://stackoverflow.com/questions/30218802
复制相似问题