user20731251
user20731251

Reputation:

Importing a file in another folder in a parent directory

I know that maybe you have faced this question many times. But since I couldn't find a solution to answer this question, I wanted to write it here again. For example:

main/
  model/
    mod1.py
  lib/
    mod2.py

I have a folder structure as above. I want to import the mod2.py file in the lib folder to the mod1.py file in the model folder. For this, I add the following line to the mod1 file.

lib.mod2 as mod2

But when I do this I get the following error.

No module named 'lib.mod2'

Can you help me?

Python version : 3.10.4

Upvotes: 2

Views: 1593

Answers (1)

Nishesh Tyagi
Nishesh Tyagi

Reputation: 66

if you have a folder structure like this

main/
  model/
    mod1.py
  lib/
    mod2/
    mod2.py

First, create a __init__.py in the folder from which you want to import the file. For this structure , it will look like this

main/
  model/
    mod1.py
  lib/
    mod2/
    mod2.py
    __init__.py

after this, you can type

from main.lib import mod2 and it should work correctly

Upvotes: 3

Related Questions