假设一个文件夹结构如下:
project/
grandparent.py
folder1/
parent.py
folder2/
sibling.py
current.py
如果我在current.py
中,我可以从其他文件导入using relative paths,如下所示:
from .sibling import *
from ..parent import *
如何从grandparent.py
导入?
(我已经尝试过...grandparent
和../..grandparent
)
发布于 2018-01-18 23:03:40
current.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
https://stackoverflow.com/questions/48324056
复制相似问题