Import python modules from another directory

1

I was looking for all the internet, I tried all the possible ways and I still can not import the module that I need. The tree of my project is this:

code
├── folder1
│ ├── subfolder 1
│ ├── file1.py (file to be imported)
│── folder2
│ └── main.py

    
asked by Yamila Marucci 20.01.2018 в 05:43
source

2 answers

1

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.

    
answered by 21.01.2018 / 16:49
source
1

in code:

from carpeta1.subcarpeta1.archivo import *

but in each folder and subfolder you must add a file __init__.py (it can be empty). The main use of __init__.py is to initialize Python packages. Although it may be empty as I said before, it is useful for the import of modules and packages to be more visible and orderly. I suggest you invest that. Greetings!

    
answered by 20.01.2018 в 06:18