How to import Python libraries that are in another hierarchy?

Asked

Viewed 2,527 times

3

I have the following directory structure

src\
    conectores\
              mysql.py
    bibliotecas
    auxiliares
teste\
    chamarMysql.py

In the above structure as I can from inside the test file call Myql.py, call a class that is in src mysql connectors.py?

2 answers

3

To make him understand that the other files are modules, create a file __init__.py empty in each folder.

If what you are running is in the root folder (before src and teste), the import look something like:

from src.conectores import mysql
mysql.seu_metodo()

If it is not in the root folder, you will need some solution to match the one described here: https://stackoverflow.com/questions/714063/importing-modules-from-parent-folder

0

Just put an empty file with the name in the same folder:

__init__.py

For example:

src\
    conectores\
              __init__.py
              mysql.py
    bibliotecas
    auxiliares
teste\
    chamarMysql.py

All folders belonging to your project should have the same file.

  • Excuse the ignorance, but and in the file I am working from there I put only the name of the file without the . py, as I normally do when files are in the same directory?

  • @Brunobermann should put a filename init.py in all folders and subfolders of your python project.

  • I just don’t understand how I import the file that is one level below and inside another directory with subdirectory.

  • As usual, just put in this case the "import mysql" line in the file where you want to import the module. No need to set the directory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.