[Solved] Python Project Import Module Error: ModuleNotFoundError

Question

Importing a custom module in the project reports an error ModuleNotFoundError. The project directory structure is as follows. When in a.script.py from bc script.py, it prompts that the b module cannot be found, and the __init__.py file created in the b directory still reports an error.

Solution:

There are several methods of online search:

  1. If you use pycharm, you can right-click on the file directory location (not pycharm, visual inspection is useful)

2. import sys (Working)
sys.path.append(‘The address of the reference module’)
3. Create in the folder that needs to be imported __init.py__ (Not Working)
4. Direct export PYTHONPATH=path in linux (Working)

 

Summary

  • If the imported module and the main program are in the same directory, import directly.
  • If the imported module is in a subdirectory of the directory where the main program is located, you can add an __init__.py file to the subdirectory, which makes the python interpreter treat the directory as a package, and then you can directly “import the subdirectory. Module” “.
  • If the imported module is in the parent directory of the directory where the main program is located, the above two are not feasible, and the path needs to be modified.

1.

The following method can be used, but it is a one-time thing.
 
import sys  
sys.path.append('address of the referenced module')  
 
 
File directory structure, need to be in the a.script.py filefrom b.c.1.py report error module not found
test
├── a
│ ├── _init_paths.py
│ └── script.py
└── b
    ├── c
    │ └── 1.py
    └── d
Suggested forms.
1. Write import sys sys.path.append('address of referenced module') directly at the beginning of the script.py file to add the path.
2. Create the _init_paths.py script in the a directory, and then just import _init_paths in script.py.
 
#_init_paths.py
import os
import sys
 
def add_path(path):
    """Add path to sys system path
    """
    if path not in sys.path:
        sys.path.append(path)
 
current_dir = os.path.dirname(__file__)
parent_dir = os.path.dirname(current_dir)
add_path(parent_dir)

2.Modify the environment variables directly, you can use export PYTHONPATH=path to add in linux.

Read More: