-1

If I have the following file structure in python:

    directory1
    ├── directory2
    │   └── file2
    └── file1

where directory 2 is a sub directory of directory 1 and assuming that neither is a package, how do I reference the file1 module from file2 assuming I am using sys.path? What import statement would I used in file 2 assuming I have x=1 in file 1 and i would like to print out the value of x in file2?

1
  • 1
    typically you're encouraged to not do that kind of thing and have a strict hierarchy/composition of modules where top-level modules only depend on modules parallel or lower to their own directory or in the python module path. Commented Jan 28, 2013 at 2:28

2 Answers 2

1

If directory1 and directory2 are both in sys.path as absolute paths, regardless if one is a subdirectory of the other, then you can import both files with simple statements (I'm assuming they've been named with .py extension at least):

# in file 1:
import file2

# in file 2:
import file1

Then you'd access contents as usual:

# in file 2
import file1
print file1.x

If you need to setup sys.path within file2, then use something like this:

# in file 2
import sys
import os.path
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,path)

import file1
print file1.x
Sign up to request clarification or add additional context in comments.

1 Comment

how would you use sys.path to put them in the system path though?
0
└── directory1
    ├── directory2
    │   └── file2.py
    └── file1.py

$ cat directory1/file1.py

x=1

$ cat directory1/directory2/file2.py

import sys 
from os.path import  dirname, realpath
sys.path.append(dirname(realpath(__file__)) + '/..')
sys.path.append('..')

from file1 import x

print x

$ python directory1/directory2/file2.py

1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.