It is not very elegant, but at least it is the only way I found starting from a folder back:
import sys
sys.path.append("..")
from carpeta1.subcarpeta1.archivo1 import *
In your case, main.py
in carpeta2
you want to import a module that physically and relative to main.py
is in: ../carpeta1/subcarpeta1/archivo1.py
, so we add to path
the folder root
of your project with sys.path.append("..")
, keep in mind that if you did it from a deeper level you should do sys.path.append("../..")
. With this, it is already possible to do from carpeta1.subcarpeta1.archivo1 import *
. Keep in mind not to add spaces to the name of the module to be imported, nor to the subfolders.
Another way is to use importlib , which also allows you to solve the problem of names of modules with points or other characters that invalidate a% traditional import
. Suppose we have a routine fun_en_archivo_py()
in code/carpeta1/subcarpeta1
we can from main.py
do the following:
import importlib.util
spec = importlib.util.spec_from_file_location("archivo", "../carpeta1/subcarpeta1/archivo.py")
archivo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(archivo)
# Para invocar la rutina anteponemos el nombre del módulo
archivo.fun_en_archivo_py()
What yes, this is functional if I do not understand badly from the version Python 3.5+ or higher.