Search code examples
pythonubuntuflask

How to fix error "ModuleNotFoundError: No module named ..."?


I'm designing a website. The project structure is

project\
 back_end\
  __init.py__
  main.py

In init.py,

from flask import Flask

def create_app():
    app = Flask(__name__)    
    return app

In main.py

from back_end import create_app

app = create_app()
@app.route("/")
def home():
    return "hello world"

When I hit run in VS Code, there is error ModuleNotFoundError: No module named 'back_end'.

I type python -m back_end.main in the command line, the code works. I also tried to rename the back_end package to b. The error still persists. Is it related to defining an environment variable? I am using Ubuntu 24.04.


Solution

  • One, it is __init__.py not __init.py__. Two, your main.py file needs to be in your project/ directory, not project/back_end/. A revised file structure would look like this:

    project\
      back_end\
        __init__.py
      main.py
    

    Also, for a simple project like the structure you described, you wouldn’t need to have multiple files like that. A single main.py file would easily suffice.