【发布时间】:2014-01-27 03:41:40
【问题描述】:
在几个 SO 的问题中,有这些行可以访问代码的父目录,例如os.path.join(os.path.dirname(__file__)) returns nothing 和 os.path.join(os.path.dirname(__file__)) returns nothing
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() 添加代码访问的路径。但是下面这条神秘的线是什么,它的真正含义是什么?
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
有没有其他方法可以达到同样的目的,追加where代码的父目录?
出现这个问题是因为我跨目录调用函数,有时它们共享相同的文件名,例如script1/utils.py 和 script2/utils.py。我正在从script1/test.py 调用一个函数,该函数调用script2/something.py 包含一个调用script2/utils.py 的函数和以下代码
script1/
utils.py
src/
test.py
script2/
utils.py
code/
something.py
test.py
from script2.code import something
import sys
sys.path.append('../')
import utils
something.foobar()
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()
【问题讨论】:
-
只是一个问题,你是说你需要这样做才能
import utils?我没有正确理解最后一部分。
标签: python import path operating-system directory