我想从 Python 脚本中获取当前目录的父目录。例如,/home/kristina/desire-directory/scripts
在这种情况下,我从期望路径启动脚本是/home/kristina/desire-directory
我知道sys.path[0]
从sys
。但我不想解析sys.path[0]
结果字符串。有没有其他方法可以在 Python 中获取当前目录的父目录?
要获取包含脚本的目录的父目录(无论当前工作目录如何),您需要使用__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
模块(在 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')
并获取当前工作目录的父目录
from pathlib import Path
d = Path().resolve().parent
请注意,这d
是一个Path
实例,并不总是很方便。您可以str
在需要时轻松将其转换为:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
Path.parent
从pathlib
模块中使用:
from pathlib import Path
# ...
Path(__file__).parent
您可以使用多个调用来parent
在路径中走得更远:
Path(__file__).parent.parent
这对我有用(我在 Ubuntu 上):
import os
os.path.dirname(os.getcwd())
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
'..'
返回当前目录的父级。
import os
os.chdir('..')
现在您的当前目录将是/home/kristina/desire-directory
.
您可以简单地使用../your_script_name.py
例如假设您的 python 脚本的路径是trading system/trading strategies/ts1.py
. 要指volume.csv
位于trading system/data/
. 您只需将其称为../data/volume.csv
import os def parent_directory(): # 创建当前工作目录的父级的相对路径 path = os.getcwd() parent = os.path.dirname(path)
relative_parent = os.path.join(path, parent) # Return the absolute path of the parent directory return relative_parent
打印(父目录())
import os
import sys
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__)))
print(d)
path1 = os.path.dirname(os.path.realpath(sys.argv[0]))
print(path1)
path = os.path.split(os.path.realpath(__file__))[0]
print(path)
from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])