How to Import a class from a different folder in p

2019-03-01 07:00发布

问题:

     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 ?

回答1:

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.