python:向上两级获取目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27844088/
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 02:21:26  来源:igfitidea点击:

python: get directory two levels up

pythonpathoperating-systemdirectory

提问by jramm

Ok...I dont know where module xis, but I know that I need to get the path to the directory two levels up.

好的...我不知道模块在哪里x,但我知道我需要获得两级目录的路径。

So, is there a more elegant way to do:

那么,有没有更优雅的方法来做:

import os
two_up = os.path.dirname(os.path.dirname(__file__))

Solutions for both Python 2 and 3 are welcome!

欢迎提供适用于 Python 2 和 3 的解决方案!

采纳答案by Ffisegydd

You can use pathlib. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip.

您可以使用pathlib. 不幸的是,这仅在 Python 3.4 的 stdlib 中可用。如果您有旧版本,则必须在此处安装 PyPI 的副本。这应该很容易使用pip.

from pathlib import Path

p = Path(__file__).parents[1]

print(p)
# /absolute/path/to/two/levels/up

This uses the parentssequence which provides access to the parent directories and chooses the 2nd one up.

这使用parents提供对父目录的访问的序列并选择第二个。

Note that pin this case will be some form of Pathobject, with their own methods. If you need the paths as string then you can call stron them.

请注意,p在这种情况下将是某种形式的Path对象,具有自己的方法。如果您需要将路径作为字符串,那么您可以调用str它们。

回答by Sebi2020

Very easy:

好简单:

Here is what you want:

这是你想要的:

import os.path as path

two_up =  path.abspath(path.join(__file__ ,"../.."))

回答by M. Murphy

Personally, I find that using the os module is the easiest method as outlined below. If you are only going up one level, replace ('../..') with ('..').

就个人而言,我发现使用 os 模块是最简单的方法,如下所述。如果您只上一级,请将 ('../..') 替换为 ('..')。

    import os
    os.chdir('../..')

--Check:
    os.getcwd()

回答by AlanSE

I don't yet see a viable answer for 2.7 which doesn't require installing additional dependencies and also starts from the file's directory. It's not nice as a single-line solution, but there's nothing wrong with using the standard utilities.

我还没有看到 2.7 的可行答案,它不需要安装额外的依赖项并且也从文件的目录开始。作为单行解决方案并不好,但使用标准实用程序并没有错。

import os

grandparent_dir = os.path.abspath(  # Convert into absolute path string
    os.path.join(  # Current file's grandparent directory
        os.path.join(  # Current file's parent directory
            os.path.dirname(  # Current file's directory
                os.path.abspath(__file__)  # Current file path
            ),
            os.pardir
        ),
        os.pardir
    )
)

print grandparent_dir

And to prove it works, here I start out in ~/Documents/notesjust so that I show the current directory doesn't influence outcome. I put the file grandpa.pywith that script in a folder called "scripts". It crawls up to the Documents dir and then to the user dir on a Mac.

为了证明它有效,我在这里开始~/Documents/notes只是为了显示当前目录不会影响结果。我将grandpa.py带有该脚本的文件放在名为“scripts”的文件夹中。它爬行到文档目录,然后爬到 Mac 上的用户目录。

(testing)AlanSE-OSX:notes AlanSE$ echo ~/Documents/scripts/grandpa.py 
/Users/alancoding/Documents/scripts/grandpa.py
(testing)AlanSE-OSX:notes AlanSE$ python2.7 ~/Documents/scripts/grandpa.py 
/Users/alancoding

This is the obvious extrapolation of the answer for the parent dir. Better to use a general solution than a less-good solution in fewer lines.

这是对父 dir 答案的明显推断。在更少的行中使用通用解决方案比使用不太好的解决方案更好。

回答by Lucidious

I have found that the following works well in 2.7.x

我发现以下在 2.7.x 中运行良好

import os
two_up = os.path.normpath(os.path.join(__file__,'../'))

回答by Axel Heider

You can use this as a generic solution:

您可以将其用作通用解决方案:

import os

def getParentDir(path, level=1):
  return os.path.normpath( os.path.join(path, *([".."] * level)) )

回答by zerocog

For getting the directory 2 levels up:

为了让目录 2 升级:

 import os.path as path
 two_up = path.abspath(path.join(os.getcwd(),"../.."))

回答by andyhasit

I was going to add this just to be silly, but also because it shows newcomers the potential usefulness of aliasing functions and/or imports.

我打算添加这个只是为了愚蠢,但也是因为它向新手展示了别名函数和/或导入的潜在用途。

Having written it, I think this code is more readable (i.e. lower time to grasp intention) than the other answers to date, and readability is (usually) king.

写完之后,我认为这段代码比迄今为止的其他答案更具可读性(即掌握意图的时间更短),并且可读性(通常)是王道。

from os.path import dirname as up

two_up = up(up(__file__))

Note: you only want to do this kind of thing if your module is very small, or contextually cohesive.

注意:如果你的模块非常小,或者上下文内聚,你只想做这种事情。

回答by zhukovgreen

More cross-platform implementation will be:

更多的跨平台实现将是:

import pathlib
two_up = (pathlib.Path(__file__) / ".." / "..").resolve()

Using parentis not supported on Windows. Also need to add .resolve(), to:

parentWindows 不支持使用。还需要添加.resolve(), 到:

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows)

使路径成为绝对路径,解析途中的所有符号链接并对其进行规范化(例如在 Windows 下将斜杠转换为反斜杠)

回答by pythinker

The best solution (for python >= 3.4) when executing from any directory is:

从任何目录执行时的最佳解决方案(对于 python >= 3.4)是:

from pathlib import Path
two_up = Path(__file__).resolve().parents[1]