[英]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.