Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModuleNotFoundError in Python

I have a PyCharm project organized as follows:

---project folder
-----------utilities
-----------------file.py
-----------------file2.py
-----------work
-----------------main.py

in main.py I'm using some functions from the utilities package as follows:

from utilities.file import function, another_function

in PyCharm I can run it and it works.

When I run it on the terminal I hit

Traceback (most recent call last):
  File "work\main.py", line 13, in <module>
    from utilities.file import function
ModuleNotFoundError: No module named 'utilities'

Someone knows why and how to fix it?

like image 483
User Avatar asked Oct 19 '25 04:10

User


2 Answers

When using the terminal, The Python interpreter needs to know to path to your imported module.

Try this

import sys
sys.path.append('my/path/to/myModule/dir')
import myModule

However, a better approach would be setting PYTHONPATH to your project directory like this

set PYTHONPATH=my/path/to/project
like image 106
Yash Avatar answered Oct 21 '25 17:10

Yash


Use from ..utilities.file import function, another_function instead

Explanation: double dots will go up by one directory, and then you will access utilities folder, and then you will import file

Also, create an empty file named __init__.py as recommended by my colleague. Please notice the double underscore.

like image 36
Ambitions Avatar answered Oct 21 '25 17:10

Ambitions



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!