Home>
How to import multiple continuous files with python

Environment:
Python 3.7.2
macOS

  • Import sub1 normally from main.py

Currently, I am writing a python3 program with the following directory structure and source code.

├── main.py
└── modules
    ├── sub1.py
    └── sub2.py
# main.py
from modules import sub1
if __name__ == '__main__':
    sub1.sub1_func ()
# modules/sub1.py
import sub2
def sub1_func ():
    sub2.sub2_func ()
if __name__ == '__main__':
    sub1_func ()
# modules/sub2.py
def sub2_func ():
    print ('sub2')

is
main.py imports sub1.py and uses sub1_func () in sub1,
sub1_func () refers to sub2.py sub2_func () in the same directory as sub1.py.
If i run main.py at this time,ModuleNotFoundError: No module named 'sub2'will appear.

Therefore, considering the thing seen from main.py, the sub1.py import statement was changed fromimport sub2tofrom modules import sub2The correct operation as expected was confirmed. ("Sub2" is output)

However, when sub1.py is executed in this state,ModuleNotFoundError: No module named 'modules'will appear.

sub1 is going to be referenced from other modules, so is there any way to import sub1 normally from main.py with import of sub1 asimport sub2? .
In the first place, isn't it very good to have such a file structure?

If i am familiar with python, would you please teach me?

  • Answer # 1

    Rewrite import of

    sub1.py.

    # modules/sub1.py
    from .import sub2

    Relative import

  • Answer # 2

    The python import is referenced relative to the path when it is executed.
    To reference relative to the location of the file instead of the runtime path

    import .foo


    Like, you need to write explicitly.

Related articles