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

拜拜、爱过 提交于 2019-12-31 03:24:08

问题


     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.



来源:https://stackoverflow.com/questions/33773202/how-to-import-a-class-from-a-different-folder-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!