In this post we will discuss how to resolve the error as ModuleNotFoundError: No module named ‘src’, when you read data from another py file
Let’s see one scenario which throws this error
Project structure –
SampleProject
| --src
| -- _init__.py
| -- data
| -- __init__.py
| -- app.py
| util
| __init__.py
| appReader.py
app.py
# Author - qavalidation.com | youtube.com/qavbox # app.py username = "qavbox" password = "qavbox001"
# Author - qavalidation.com | youtube.com/qavbox # appReader.py from src.data import app print(app.username)
Now to run the above code –
python3 src/util/appReader.py
you will get error –
Traceback (most recent call last): File "src/util/appReader.py", line x, in <module> from src.data import app ModuleNotFoundError: No module named 'src'
This above error is because python considers the appReader.py as script that isn’t part of any package.
Python will search for modules in the same directory as the script, i.e. src/util/
:
src
is not in src/util/
, so it throws the error.
To avoid this error you need to have -m switch with module name, then the given module is located on the Python module path and executed as a script.
so run successfully – you can run as
python3 -m src.util.appReader
The output would be –
qavbox
Hope this helps!
Thank you sir..this one really helped me. No where I could find a solution for this error and this single line of code made it!!