关于import:os.path.abspath(os.path.join(os.path.dirname(__ file __),os.path.pardir))是什么意思? 蟒蛇

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)

我知道os.path.abspath()返回某些内容的绝对路径,sys.path.append()添加了要访问的代码的路径。 但是下面这个神秘的界限是什么,它究竟意味着什么?

1
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))

是否有另一种方法可以实现附加代码所在位置的父目录的相同目的?

出现此问题的原因是我在跨目录调用函数,有时它们共享相同的文件名,例如 script1/utils.pyscript2/utils.py。 我从script1/test.py调用一个函数,其中调用script2/something.py包含一个调用script2/utils.py的函数和以下代码

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种常数:

  • abspath返回路径的绝对路径
  • join加入路径字符串
  • dirname返回文件的目录
  • __file__指的是script的文件名
  • pardir返回OS中父目录的表示形式(通常为..)
  • 因此,表达式以多平台安全的方式返回执行脚本的完整路径名。没有必要硬连线任何方向,这就是它如此有用的原因。

    可能有其他方法来获取文件所在位置的父目录,例如,程序具有当前工作目录os.getcwd()的概念。所以做os.getcwd()+'/..'可能会有效。但这非常危险,因为可以更改工作目录。

    此外,如果要导入文件,工作目录将指向导入文件,而不是导入文件,但__file__始终指向实际模块的文件,因此它更安全。

    希望这可以帮助!

    编辑:P.S。 - Python 3通过让我们以面向对象的方式处理路径来大大简化这种情况,因此上面的行变为:

    1
    2
    from pathlib import Path
    Path(__file__).resolve().parent.parent

    __file__表示代码正在执行的文件

    os.path.dirname(__file__)为您提供文件所在的目录

    os.path.pardir代表"..",表示当前目录之上的一个目录

    os.path.join(os.path.dirname(__file__), os.path.pardir)加入目录名称和".."

    os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))解析上述路径,并为您的文件所在目录的父目录提供绝对路径