8

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.

RexLeong
  • 141
  • 1
  • 2
  • 9

1 Answers1

6

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
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thanks, the syntax is correct, but now it give me another error: `SystemError: Parent module '' not loaded, cannot perform relative import`, any solution? – RexLeong Dec 20 '18 at 06:17
  • 1
    You should run your project from `main.py` and do `from mysql import read` in `main.py` instead. – blhsing Dec 20 '18 at 06:23
  • 1
    `main.py` will call the function from `read.py`, so thats why I need to use relative import, Btw `from conf import mysql` does not work. – RexLeong Dec 20 '18 at 06:33
  • relative import does not work in python4.* – Nick May 25 '21 at 14:36