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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With