abcde
abcde

Reputation: 85

How to Import a class from a different folder in python?

     common/src/validation/file1.py

In the common/src/validation folder "_init_" is defined.

     common/test/validation/file2.py
     common/test/validation/case/file3.py

In file2.py and file3.py, I want to import class from file1.py.

Im giving the following line in file2.py and file3.py.:

      from file1 import class1  

I currently get error:

      #ImportError: No module named file1

what should be the sys.path.append ?

Upvotes: 4

Views: 13321

Answers (1)

shahram kalantari
shahram kalantari

Reputation: 863

You should add the module to your python PATH in the beginning of your script. So in the beginning of your file2.py and file3.py, you should have the following:

sys.path.append('/src/validation/')
from file1 import class1

And don't forget to create the __init__.py in your /src/validation/ directory.

Upvotes: 7

Related Questions