簡體   English   中英

在Python中的不同目錄中導入文件

[英]Importing files in different directories in Python

我有這樣的目錄結構:

dir/
   frontend.py
   dir1/main.py
   dir2/backend.py
  • 如何在main中的Python中導入后端?
  • 如何在main中的Python中導入前端?

在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM