Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import module from parent directory

Take a look at my file structure:

main/
    main.py
    __init__.py

    mysql/
        read.py
        __init__.py

    conf/
        mysql.py
        loc.py
        __init__.py

conf/mysql.py contains the information of a mysql server (port,hostname,etc...)

read.py is used to acquire and read value from a MySQL DB by connect to the server specified in conf/mysql.py.

What I wanted to achieve is to let read.py import conf/mysql.py, so I tried:

from conf import mysql
import main.conf.mysql

Both of them are not working. It gives me ImportError: No Module Name 'main' and ImportError: No Module Named 'conf', import conf/mysql.py only work in main.py

I know that appending to sys.path will work, but for some reasons, I don't wanna do that.

Any solutions to work around this issue? Thanks in advance and sorry for this complicated question.

like image 337
RexLeong Avatar asked Dec 20 '18 06:12

RexLeong


People also ask

How do I import a module from the outside directory?

Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.

How do I import an entire module?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

How does Python import modules from some other directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.


Video Answer


1 Answers

Since the main directory is the root directory of your project, you should not include main in your absolute import:

from conf import mysql

or with relative import, you can do:

from ..conf import mysql
like image 91
blhsing Avatar answered Nov 15 '22 09:11

blhsing