2

To give an example, my python files are structured like:

C:\
  folder1\
    file1.py
  folder2\
    file2.py

Let's assume there is a class named Class1 in the module file1 (and an empty __init__.py file as well, if you like). How can I import Class1 in file2? I always get an "ImportError: No module named folder1" when trying to import from folder1; things like "sys.path.insert(0, '../folder1')" don't work for me.

Would I have to add "C:\" to the system environment variable "PATH" (note that I am not working in site-packages folder)?

stecrz
  • 55
  • 5
  • Possible duplicate of [Import a module from a relative path](http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path) – WhatsThePoint Feb 22 '17 at 13:20
  • Don't think so, as I am working with two different directories. "from folder1.file1 import Class1" always gives me an ImportError. – stecrz Feb 22 '17 at 13:27
  • Probably need to set your PYTHONPATH to have 'C:\folder2'. And don't forget to add `__init__.py` to folder2 – Edgar Feb 22 '17 at 13:28
  • I don't have PYTHONPATH in my system environment variables. Should I simply add the variable with C:\folder1 as the only content? – stecrz Feb 22 '17 at 13:30

1 Answers1

2

You need to have __init__.py in both the folders.

Then you can use the sys module to dynamically append to the python path

sys.append.path(../folder1)

from file1 import Class1 will work now. (Tested on Linux)

But you still cannot do something like from folder1.file1 import Class1

pmuntima
  • 640
  • 5
  • 13