如何获取父目录位置

问题:如何获取父目录位置

这段代码是在b.py中获取templates / blog1 / page.html:

path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))

但我想获取父目录位置:

aParent
   |--a
   |  |---b.py
   |      |---templates
   |              |--------blog1
   |                         |-------page.html
   |--templates
          |--------blog1
                     |-------page.html

以及如何获取父位置

谢谢

更新:

这是对的:

dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))

要么

path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))

this code is get the templates/blog1/page.html in b.py:

path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))

but i want to get the parent dir location:

aParent
   |--a
   |  |---b.py
   |      |---templates
   |              |--------blog1
   |                         |-------page.html
   |--templates
          |--------blog1
                     |-------page.html

and how to get the aParent location

thanks

updated:

this is right:

dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))

or

path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))

回答 0

您可以重复应用dirname来爬高:dirname(dirname(file))。但是,这只能到达根包。如果有问题,请使用os.path.abspathdirname(dirname(abspath(file)))

You can apply dirname repeatedly to climb higher: dirname(dirname(file)). This can only go as far as the root package, however. If this is a problem, use os.path.abspath: dirname(dirname(abspath(file))).


回答 1

os.path.abspath不会验证任何内容,因此,如果我们已经向其追加字符串,__file__则无需理会dirname或加入其中的任何一个。只需将其__file__视为目录并开始爬山:

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

这远不os.path.abspath(os.path.join(os.path.dirname(__file__),".."))及易处理dirname(dirname(__file__))。攀登两个以上的水平开始变得荒谬。

但是,由于我们知道要爬多少层,我们可以用一个简单的小函数来清理它:

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'

os.path.abspath doesn’t validate anything, so if we’re already appending strings to __file__ there’s no need to bother with dirname or joining or any of that. Just treat __file__ as a directory and start climbing:

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

That’s far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) and about as manageable as dirname(dirname(__file__)). Climbing more than two levels starts to get ridiculous.

But, since we know how many levels to climb, we could clean this up with a simple little function:

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'

回答 2

相对路径pathlibPython 3.4+中的模块一起使用:

from pathlib import Path

Path(__file__).parent

您可以使用多个调用来parent进一步进行以下操作:

Path(__file__).parent.parent

作为指定parent两次的替代方法,可以使用:

Path(__file__).parents[1]

Use relative path with the pathlib module in Python 3.4+:

from pathlib import Path

Path(__file__).parent

You can use multiple calls to parent to go further in the path:

Path(__file__).parent.parent

As an alternative to specifying parent twice, you can use:

Path(__file__).parents[1]

回答 3

os.path.dirname(os.path.abspath(__file__))

应该给你通往的道路a

但是,如果b.py当前执行的是文件,则只需执行以下操作即可

os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
os.path.dirname(os.path.abspath(__file__))

Should give you the path to a.

But if b.py is the file that is currently executed, then you can achieve the same by just doing

os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))

回答 4

os.pardir是一种更好的方法../,更具可读性。

import os
print os.path.abspath(os.path.join(given_path, os.pardir))  

这将返回给定路径的父路径

os.pardir is a better way for ../ and more readable.

import os
print os.path.abspath(os.path.join(given_path, os.pardir))  

This will return the parent path of the given_path


回答 5

一种简单的方法可以是:

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

A simple way can be:

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

回答 6

可能是加入两个..文件夹,以获取父文件夹的父文件夹?

path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))

May be join two .. folder, to get parent of the parent folder?

path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))

回答 7

使用以下命令跳到上一个文件夹:

os.chdir(os.pardir)

如果您需要多次跳转,那么在这种情况下,使用简单的装饰器是一个好而简单的解决方案。

Use the following to jump to previous folder:

os.chdir(os.pardir)

If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.


回答 8

这是另一个相对简单的解决方案:

  • 不使用dirname()(在“ file.txt”这样的一级参数或“ ..”这样的相对父级上不能按预期工作)
  • 不使用abspath()(避免对当前工作目录进行任何假设),而是保留路径的相对字符

它只是使用normpathjoin

def parent(p):
    return os.path.normpath(os.path.join(p, os.path.pardir))

# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
        'dir/file.txt', '../up/', '/abs/path']:
    print parent(p)

结果:

.
foo/bar
with/trailing
dir
..
/abs

Here is another relatively simple solution that:

  • does not use dirname() (which does not work as expected on one level arguments like “file.txt” or relative parents like “..”)
  • does not use abspath() (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths

it just uses normpath and join:

def parent(p):
    return os.path.normpath(os.path.join(p, os.path.pardir))

# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
        'dir/file.txt', '../up/', '/abs/path']:
    print parent(p)

Result:

.
foo/bar
with/trailing
dir
..
/abs

回答 9

我认为用这个更好:

os.path.realpath(__file__).rsplit('/', X)[0]


In [1]: __file__ = "/aParent/templates/blog1/page.html"

In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'

In [4]: __file__ = "/aParent/templates/blog1/page.html"

In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'

In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'

In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'

I think use this is better:

os.path.realpath(__file__).rsplit('/', X)[0]


In [1]: __file__ = "/aParent/templates/blog1/page.html"

In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'

In [4]: __file__ = "/aParent/templates/blog1/page.html"

In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'

In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'

In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'

回答 10

我试过了:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))

I tried:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))