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

alv*_*vas 14 python directory import operating-system path

在一些SO的问题有这些行访问代码的父目录,如os.path.join(os.path.dirname(__ FILE__))没有返回值os.path.join(os.path.dirname(__ FILE__) )什么都不返回

import os, sys
parentddir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
sys.path.append(parentddir)
Run Code Online (Sandbox Code Playgroud)

我理解os.path.abspath()返回某些东西的绝对路径并sys.path.append()添加代码访问的路径.但是下面这个神秘的界限是什么,它究竟意味着什么?

os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
Run Code Online (Sandbox Code Playgroud)

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

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

script1/
        utils.py
        src/
            test.py

script2/
        utils.py
        code/
            something.py
Run Code Online (Sandbox Code Playgroud)

test.py

from script2.code import something
import sys
sys.path.append('../')
import utils

something.foobar()
Run Code Online (Sandbox Code Playgroud)

something.py

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()
Run Code Online (Sandbox Code Playgroud)

Pau*_* Bu 33

无论脚本位置如何,这都是一种引用路径的聪明方法.你所指的神秘线是:

os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
Run Code Online (Sandbox Code Playgroud)

有3种方法和2种常数:

  1. abspath 返回路径的绝对路径
  2. join 加入路径字符串
  3. dirname 返回文件的目录
  4. __file__是指script文件名
  5. pardir返回OS中父目录的表示(通常..)

因此,表达式以多平台安全的方式返回执行脚本完整路径名.没有必要硬连线任何方向,这就是它如此有用的原因.

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

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

希望这可以帮助!


pra*_*een 14

__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)) 解析上面的路径,并为您的文件所在目录的父目录提供绝对路径