Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading