EN VI

Python: Import directory from a file inside that directory?

2024-03-15 17:00:06
How to Python: Import directory from a file inside that directory

I'm sorry if the title is confusing since English is not my first language. What I have trouble is running a python script that calls import of its own directory. The folder structure is like this:

MyProject 
    |--Utils
          |-- util
          |     |-- __init__.py
          |     |-- run.py
          |-- __init__.py
          |-- test.py

And the code of test.py is as following

import Utils.util

if __name__ == '__main__':
   # Do something

When running test.py, I get this error

ModuleNotFoundError: No module named 'Utils'

Is there anyway to call import that's suitable for this folder structure? If it's possible, someone can please help me naming this problem for better searches?

I have tried create a new script in the root folder which runs normally. However, what if I want to store testing code like test.py in modular folders, the import command is not running

Solution:

The error "ModuleNotFoundError: No module named 'Utils'" occurs because Python doesn't automatically search for modules within subdirectories unless they are treated as packages.

from .util import
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login