Search code examples
python-3.xpython-3.4

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.


Solution

  • 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