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

半腔热情 提交于 2019-12-11 08:24:05

问题


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

  • mywebsitefolder
    • myfolder
      • api_supply
        • tests (contains all my tests with many files)
        • init.py
        • serializers.py
        • urls.py
        • views.py
      • api_demand
        • tests (contains all my tests with many files)
        • init.py
        • serializers.py
        • urls.py
        • views.py
      • migrations (folder)
      • templates (folder)
      • init.py
      • admin.py
      • apps.py
      • models.py
      • tests.py
      • urls.py
      • views.py

回答1:


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)


来源:https://stackoverflow.com/questions/58990164/sys-path-insert-inserts-path-to-module-but-imports-are-not-working

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