What does os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) mean? python
在几个SO的问题中,有这些行来访问代码的父目录,例如 os.path.join(os.path.dirname(__ file __))什么都不返回,os.path.join(os.path.dirname(__ file__))什么都不返回
1 2 3 | import os, sys parentddir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(parentddir) |
我知道
1 | os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) |
是否有另一种方法可以实现附加代码所在位置的父目录的相同目的?
出现此问题的原因是我在跨目录调用函数,有时它们共享相同的文件名,例如
1 2 3 4 5 6 7 8 9 | script1/ utils.py src/ test.py script2/ utils.py code/ something.py |
test.py
1 2 3 4 5 6 | from script2.code import something import sys sys.path.append('../') import utils something.foobar() |
something.py
1 2 3 4 5 6 7 | import os, sys parentddir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(parentddir) import utils def foobar(): utils.somefunc() |
无论脚本位置如何,这都是一种引用路径的聪明方法。你所指的神秘线是:
1 | os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) |
有3种方法和2种常数:
因此,表达式以多平台安全的方式返回执行脚本的完整路径名。没有必要硬连线任何方向,这就是它如此有用的原因。
可能有其他方法来获取文件所在位置的父目录,例如,程序具有当前工作目录
此外,如果要导入文件,工作目录将指向导入文件,而不是导入文件,但
希望这可以帮助!
编辑:P.S。 - Python 3通过让我们以面向对象的方式处理路径来大大简化这种情况,因此上面的行变为:
1 2 | from pathlib import Path Path(__file__).resolve().parent.parent |