简体   繁体   中英

python : `moduleNotFoundError` when attempting to import file from a directory

Running into moduleNotFoundError when attempting to import a file from root directory.

Directory structure for Flask App:

index.py
auth_
  - server.py
Pages
  - home.py

I am able to import home.py from Pages , but not server.py from auth_

In index.py , I am attempting to import server.py

from auth_ import server


File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
ModuleNotFoundError: No module named 'auth_'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/cli.py", line 338, in __call__
    self._flush_bg_loading_exception()
  File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception
    reraise(*exc_info)
  File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/cli.py", line 314, in _load_app
    self._load_unlocked()
  File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/cli.py", line 388, in load_app
    app = locate_app(self, import_name, name)
  File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/flask/cli.py", line 250, in locate_app
    raise NoAppException('Could not import "{name}".'.format(name=module_name))
flask.cli.NoAppException: Could not import "auth_".
from .auth_ import server

will solve your problem.

. means the current directory in which you run your script, ie index.py , so with .auth_ you have auth_ folder in the same directory with index.py and you want to call a file or folder in auth directory.

Final statement ( from.auth_ import server ) tells that you will use server.py script, which is located in auth_ folder and auth_ folder is in the same directory with your index.py .

I recommend you to look at this guide to understand absolute and relative imports in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM