![](/img/trans.png)
[英]How I can Import from a other relative folder wihout the knowledge of the path?
[英]In Python, how can I import from a grandparent folder with a relative path?
想象一下一個文件夾結構,如下所示:
project/
grandparent.py
folder1/
parent.py
folder2/
sibling.py
current.py
如果我在current.py
,則可以使用以下相對路徑從其他文件導入:
from .sibling import *
from ..parent import *
如何從grandparent.py
導入?
(我嘗試過...grandparent
和../..grandparent
)
作為確保某種程度的安全性的一種手段-以便Python模塊無法訪問不受歡迎的區域-通常禁止從父母或祖父母那里導入... 除非您創建軟件包 。
幸運的是,在Python中創建軟件包非常容易 。 您只需要在要作為軟件包一部分的每個文件夾/目錄中添加__init__.py
文件。 而且, __init__.py
文件甚至不需要包含任何內容 。 您只需要存在(可能為空)文件。
例如:
#current.py
from folder1.grandparent import display
display()
#grandparent.py
def display():
print("grandparent")
# ├── folder1
# │ ├── __init__.py
# │ ├── folder2
# │ │ ├── __init__.py
# │ │ └── folder3
# │ │ ├── __init__.py
# │ │ └── current.py
# │ └── grandparent.py
這不是OP的問題,而是高度相關的且值得一提:如果您導入目錄而不是模塊(文件),那么您就是在導入__init__.py
文件。 例如,
import folder1
實際上是在folder1
目錄中執行__init__.py
文件的導入。
最后,雙下划線經常被使用,它被縮短為dunder 。 因此,在講話時,您可以說“ dunder init”來引用__init__.py
。
import os
import sys
FILE_ABSOLUTE_PATH = os.path.abspath(__file__) # get absolute filepath
CURRENT_DIR = os.path.dirname(FILE_ABSOLUTE_PATH) # get directory path of file
PARENT_DIR = os.path.dirname(CURRENT_DIR) # get parent directory path
BASE_DIR = os.path.dirname(PARENT_DIR) # get grand parent directory path
# or you can directly get grandparent directory path as below
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR) # append the path to system
import grandparent
from folder1 import parent # this way you can import files from parent directory too instead of again appending it to system path
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.