0

this is a visual representation of my directory :

enter image description here

here is the code snippet from test1.py

....
def foo():
    f=read("./test1.dat","r")
....

here is the code of test2.py

import imp

TEST1 = imp.load_source('test1', '../test1.py')


def test2():
    TEST1.foo()

running test2.py

cd subdir
python test2.py

got IOERROR: No Such file or directory : "./test1.dat"

my question is :

if I don't change the structure of directory, for example move test2.py to its parent directory, is it possible to make module test1 find the correct file when calling it in module test2?

camino
  • 10,085
  • 20
  • 64
  • 115

1 Answers1

0

This will give you the path to a module that was loaded:

import a_module
print a_module.__file__

To get the directory of the module:

import os, a_module
path = os.path.dirname(a_module.__file__)

Putting it all together, I'd use this approach if you're looking for files relative to another module:

from test1.py

def foo(path):
    f=read(path,"r")

from test2.py

import os, test1
path = os.path.dirname(test1.__file__)
test1.foo(path + "/test1.dat")
Kyle
  • 4,202
  • 1
  • 33
  • 41
  • Thanks , but in function foo ,it has no input parameter – camino Mar 20 '13 at 18:29
  • I think it should be better to replace relative path with __file__ in test1.py. It seems it was not a good idea to use relative path in python module:) – camino Mar 20 '13 at 18:39