从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:05:15  来源:igfitidea点击:

Get parent of current directory from Python script

pythonsyssys.path

提问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/scriptsthe 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.dirnametwice:

在脚本内部使用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.dirnameas 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 pathlibmodule (available in Python 3.4 or newer).

您还可以使用该pathlib模块(在 Python 3.4 或更高版本中可用)。

Each pathlib.Pathinstance have the parentattribute referring to the parent directory, as well as the parentsattribute, which is a list of ancestors of the path. Path.resolvemay be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absoluteinstead 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 dis a Pathinstance, which isn't always handy. You can convert it to streasily 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.parentfrom the pathlibmodule:

Path.parentpathlib模块使用:

from pathlib import Path

# ...

Path(__file__).parent

You can use multiple calls to parentto 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.pyFor example suppose the path to your python script is trading system/trading strategies/ts1.py. To refer to volume.csvlocated 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