Python ImportError loading module within subfolder

2019-06-04 07:18发布

问题:

I have the following structure

abc/
    __init__.py
    settings.py
    tests/
       __init__.py
       test.py

in test.py, I am getting an ImportError for

#test.py
import abc.settings

回答1:

You have two ways.

Firstly, by setting the path variable

import os
import sys
sys.path.insert(0, <Complete path of abc>)

Or by using relative imports.



回答2:

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

you need to add your root directory to sys.path :

import sys
sys.path.append('path_of_root')

Aldo '..'+sys.path[0] can give you the path of abc directory !