Home > front end >  Why Python cannot find the module at the current directory?
Why Python cannot find the module at the current directory?

Time:12-07

I'm using Python 3.11.1 embeddable package. Let's say I have the following directory structure:

src  
  |---  test.py
  |---  mytest.py
test.py:
from mytest import *

After cd-ing to directory src, I run python.exe test.py, it showed me the module error:

ModuleNotFoundError: No module named 'mytest'

Changing the content of test.py to import mytest does not work. Adding an empty __init__.py does not work as well. Switching to another Python version does not work.

Note: It's fine if I use another Python which is installed by an installer.

CodePudding user response:

ModuleNotFoundError, because by default Python interpreter will check for the file in the current directory only, and need to set the file path manually to import the modules from another directory.

CodePudding user response:

To import python file from current directory you can simply do as follows:

test.py:
from .mytest import * 

here dot represent current directory where test.py is located

In order for Python to find a module, the module must be located in the same directory as the Python script you are running, or in a directory that is included in the PYTHONPATH environment variable.

  • Related