Home > Blockchain >  Python: 'ModuleNotFoundError' when trying to import module from files
Python: 'ModuleNotFoundError' when trying to import module from files

Time:10-21

i want to access config/cache.py from test.py And ,I need internal access like from config/env.py to database/modules/game.py but i get this error always:

ModuleNotFoundError: No module named 'modules'

my project tree:

project
├─ modules
│  ├─ cache
│  │  ├─ playtime.py
│  │  └─ __init__.py
│  ├─ config
│  │  ├─ cache.py
│  │  ├─ database.py
│  │  ├─ env.py
│  │  ├─ yaml.py
│  │  └─ __init__.py
│  ├─ database
│  │  └─ models
│  │     ├─ game.py
│  │     ├─ member.py
│  │     ├─ room.py
│  │     ├─ wiki.py
│  │     └─ __init__.py
│  ├─ room
│  ├─ utils
│  │  ├─ functions.py
│  │  ├─ logger.py
│  │  └─ __init__.py
│  └─ __init__.py
├─ run.py
└─ test
   └─ test.py

and inits file are like that:

from .config import *
from .utils import *
from .database import *
from .cache import *

CodePudding user response:

Python automatically insert the folder in which the main script resides to sys.path, which is a list containing folders where to find packages and modules.

So, if test.py were in folder project, that folder would be in sys.path and then you could import the modules package and any of its subpackages or modules.

import module  # main package module
from module import config   # subpackage config
from module.config import env  # module env

(Just in case, a module is a file ending in .py, and a package is a folder with a file called __init__.py inside and optionally subpackages and/or modules.)

So one solution wood be to move the file test.py to projects

Another alternative is to add the folder projects (as a str) manually to sys.path which is a simple python list before importing.

import sys
sys.append('.../projects')
from modules.config import env
  • Related