简体   繁体   中英

Importing files in different directories in Python

I have a directory structure like this:

dir/
   frontend.py
   dir1/main.py
   dir2/backend.py
  • How do I import backend in main in Python?
  • How do I import frontend in main in Python?

Have tried all the answers on Stackoverflow. Nothing seems to work.

In any folder from which you want to import source files you need to have existing init .py file.

I would advise structure like:

dir/
   main.py
   dir1/frontend.py
   dir1/__init__.py
   dir2/backend.py
   dir2/__init__.py

Then you import them in following fashion (in main.py):

import dir1.frontend
import dir2.backend

There is only one rule when it comes to importing files in a Python project.

You have to import the package relative to the directory from where the project is run.

For example in the question main.py should have something like this:

from dir.frontend import *
from dir.dir2.backend import *

But then you'll have to have something like main.py under dir/ which imports dir/dir1/main.py and then run python main.py .

So, try to keep the main.py always in the head directory so you don't have to worry about such a situation as above.

ONLY ONE RULE: Everything has to be imported relatively to the directory from where the project is run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM