Yashoraj Agarwal
Yashoraj Agarwal

Reputation: 54

ModuleNotFoundError : When importing from directory

My files are:

main.py
dir/func.py
dir/mod.py

My main.py has from dir import func
My func.py has import mod

When I run main.py it gives me:
ModuleNotFoundError: No module named 'mod'

I am using Python 3.10, so what I have read, I do not need the __init__.py file.

Now, it does work if I put from dir import mod in func.py. Is there any way to not have to do that. Is there a better, more elegant way? Because I might have to be calling func.py from different directories in the future.

Upvotes: 0

Views: 1386

Answers (1)

naif_d
naif_d

Reputation: 76

You can create a new package directory

from foldername.filename import func

make sure to include an empty _init_.py file in the directory. This file tells Python to treat the directory as a package

Upvotes: 1

Related Questions