pythondjangopathsyssys.path

Sys.path.insert inserts path to module but imports are not working


I want to import a module in a project and it gives me lots of troubles because of an import error. So I decided to write a little test to see where the problem lies. I add a folder to my sys path and try to import it. And I get an Import Error: no module found named xyz

Like this:

import sys
import os

sys.path.insert(0, os.path.abspath('../../myfolder'))
import myfolder
print(sys.path)

The sys.path is ['/Users/myuser/myproject/mywebsitefolder/myfolder/', ...]

myfolder contains an __init__.py file. Hardcoding the path to myfolder has same results. Other questions on the web solve the problem by either adding the correct path or by adding an init. But I have both I think and the problem remains.

I was under the impression that python looks in the system path for importable modules or do I misunderstand how this is supposed to work?

If I understand correctly, is there any way I can debug this further? Or could this be a problem with python versions?

Help is very much appreciated. Thanks in advance!

Edit: Here is my structure of my directories


Solution

  • Replace the code as this you dont need to add the folder to the path all you need is the path to the folder

    import sys
    import os
    
    sys.path.insert(0, os.path.abspath('../../'))
    import myfolder
    print(sys.path)