Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 830
abcde Avatar asked Oct 14 '25 18:10

abcde


1 Answers

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.

like image 102
shahram kalantari Avatar answered Oct 17 '25 06:10

shahram kalantari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!