Sunday, June 3, 2018

How to access a module from outside your file folder in Python?




How can I access modules from another folder?



Here's the file structure:




/
/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?


Answer




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 *

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...