从其他路径导入模块导致IOERROR:没有此文件或目录
这是我目录的可视化表示:
这是来自 test1.py 的代码片段:
....
def foo():
f=read("./test1.dat","r")
....
这是 test2.py 的代码:
import imp
TEST1 = imp.load_source('test1', '../test1.py')
def test2():
TEST1.foo()
正在运行 test2.py
cd subdir
python test2.py
出现了 IOERROR:没有这样的文件或目录:"./test1.dat"
我的问题是:
如果我不改变目录的结构,比如不把 test2.py 移到上级目录,是否有可能让 test1 模块在 test2 中调用时找到正确的文件?
1 个回答
0
这段代码会告诉你一个已经加载的模块的路径:
import a_module
print a_module.__file__
如果你想获取这个模块所在的目录,可以使用下面的代码:
import os, a_module
path = os.path.dirname(a_module.__file__)
把这些内容结合起来,如果你想找与另一个模块相关的文件,可以用以下方法:
在test1.py文件中:
def foo(path):
f=read(path,"r")
在test2.py文件中:
import os, test1
path = os.path.dirname(test1.__file__)
test1.foo(path + "/test1.dat")