Modules in subdirectories cannot be imported.

Asked 1 years ago, Updated 1 years ago, 142 views

When the directory structure is like this

bin/
    dir.py
    main.py
    usr/
        user.py

I am importing class dir from dir.py and class user from user.py from main.py

There is nothing wrong with dir modules in the same directory, but you cannot import user modules in subdirectories.

How do I import modules in subdirectories?

#main.py

from dir import dir
from user import user

#Code Down

Traceback (most recent call last): File "main.py", line 2, in from user import user ImportError: cannot import name user

python import

2022-09-22 16:09

1 Answers

If you are in the same directory and you cannot import it, you can create an empty file in that directory and name it __init__.py.

_init__.py is a file that sets what can be imported into a package. If this is empty, the import is considered unrestricted.

Make the same _init__.py in the subdirectory, and point if you want to import modules in the subdirectory.

So,

bin/
    dir.py
    main.py
    usr/
        user.py

In this hierarchy, the main is

from dir import dir
from usr.user import user

Please import another module.


2022-09-22 16:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.