How can I access modules from another folder?
Here's the file structure:
/<appname> /config __init__.py config.py /test test.py # I'm here
I wanted to access the functions from config.py from test.py . How would I do this?
Here is my import:
import config.config
When I run the test.py
script, it will always say:
ImportError: No module named config.config
Did I do something wrong?
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.
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.
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
Answer. No, files can be imported from different directories.
The simplest way is to modify the sys.path
variable (it defines the import search path):
# Bring your packages onto the path import sys, os sys.path.append(os.path.abspath(os.path.join('..', 'config'))) # Now do your import from config.config import *
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