[英]Importing files in different directories in Python
我有這樣的目錄結構:
dir/
frontend.py
dir1/main.py
dir2/backend.py
在Stackoverflow上嘗試了所有答案。 似乎沒有任何作用。
在要從中導入源文件的任何文件夾中,都需要具有現有的init .py文件。
我會建議這樣的結構:
dir/
main.py
dir1/frontend.py
dir1/__init__.py
dir2/backend.py
dir2/__init__.py
然后以以下方式(在main.py中)導入它們:
import dir1.frontend
import dir2.backend
在Python項目中導入文件時只有一條規則 。
您必須relative
對於運行項目的directory
導入包。
例如,在問題main.py
應具有以下內容:
from dir.frontend import *
from dir.dir2.backend import *
但是然后您必須在dir/
下有一個類似於main.py
東西,它會導入dir/dir1/main.py
然后運行python main.py
因此,請嘗試將main.py
始終保留在head directory
這樣您就不必擔心上述情況。
只有一個規則: Everything has to be imported relatively to the directory from where the project is run.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.