从 Python 脚本获取当前目录的父目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30218802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get parent of current directory from Python script
提问by Fedorenko Kristina
I want to get the parent of current directory from Python script. For example I launch the script from /home/kristina/desire-directory/scripts
the desire path in this case is /home/kristina/desire-directory
我想从 Python 脚本中获取当前目录的父目录。例如,/home/kristina/desire-directory/scripts
在这种情况下,我从期望路径启动脚本是/home/kristina/desire-directory
I know sys.path[0]
from sys
. But I don't want to parse sys.path[0]
resulting string. Is there any another way to get parent of current directory in Python?
我sys.path[0]
从sys
. 但我不想解析sys.path[0]
结果字符串。有没有其他方法可以在 Python 中获取当前目录的父目录?
采纳答案by vaultah
Using os.path
使用 os.path
To get the parent directory of the directory containing the script(regardless of the current working directory), you'll need to use __file__
.
要获取包含脚本的目录的父目录(无论当前工作目录如何),您需要使用__file__
.
Inside the script use os.path.abspath(__file__)
to obtain the absolute path of the script, and call os.path.dirname
twice:
在脚本内部使用os.path.abspath(__file__)
获取脚本的绝对路径,并调用os.path.dirname
两次:
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Basically, you can walk up the directory tree by calling os.path.dirname
as many times as needed. Example:
基本上,您可以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'
If you want to get the parent directory of the current working directory, use os.getcwd
:
如果要获取当前工作目录的父目录,请使用os.getcwd
:
import os
d = os.path.dirname(os.getcwd())
Using pathlib
使用路径库
You could also use the pathlib
module (available in Python 3.4 or newer).
您还可以使用该pathlib
模块(在 Python 3.4 或更高版本中可用)。
Each pathlib.Path
instance have the parent
attribute referring to the parent directory, as well as the parents
attribute, which is a list of ancestors of the path. Path.resolve
may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute
instead if that isn't a desired behaviour.
每个pathlib.Path
实例都有一个parent
指向父目录的parents
属性,以及一个路径祖先列表的属性。Path.resolve
可用于获取绝对路径。它还解析所有符号链接,但Path.absolute
如果这不是所需的行为,您可以改用它。
Path(__file__)
and Path()
represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory(regardless of the current working directory) you would use
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')
and to get the parent directory of the current working directory
并获取当前工作目录的父目录
from pathlib import Path
d = Path().resolve().parent
Note that d
is a Path
instance, which isn't always handy. You can convert it to str
easily when you need it:
请注意,这d
是一个Path
实例,并不总是很方便。您可以str
在需要时轻松将其转换为:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
回答by corvid
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
回答by beingzy
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])
回答by akashbw
This worked for me (I am on Ubuntu):
这对我有用(我在 Ubuntu 上):
import os
os.path.dirname(os.getcwd())
回答by Gavriel Cohen
Use Path.parent
from the pathlib
module:
Path.parent
从pathlib
模块使用:
from pathlib import Path
# ...
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
您可以使用多个调用来parent
在路径中走得更远:
Path(__file__).parent.parent
回答by marcin
'..'
returns parent of current directory.
'..'
返回当前目录的父目录。
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory
.
现在您的当前目录将是/home/kristina/desire-directory
.
回答by Yanqi Huang
You can simply use../your_script_name.py
For example suppose the path to your python script is trading system/trading strategies/ts1.py
. To refer to volume.csv
located in trading system/data/
. You simply need to refer to it as ../data/volume.csv
您可以简单地使用../your_script_name.py
例如假设您的 python 脚本的路径是trading system/trading strategies/ts1.py
. 指volume.csv
位于trading system/data/
. 您只需将其称为../data/volume.csv