Kurt Peek
Kurt Peek

Reputation: 57541

How to import a module from a different directory and have it look for files in that directory

I'm trying to import a Python module in the directory /home/kurt/dev/clones/ipercron-utils/tester. This directory contains a tester.py and a config.yml file. The tester.py includes the (leading) line

config = yaml.safe_load(open("config.yml"))

Now, from another directory, I try to import it like so:

import sys
sys.path.insert(0, "/home/kurt/dev/clones/ipercron-utils/tester")
import tester

However, I get the following error:

Traceback (most recent call last):
  File "/home/kurt/dev/clones/ipercron-compose/controller/controller_debug2.py", line 9, in <module>
    import tester
  File "/home/kurt/dev/clones/ipercron-utils/tester/tester.py", line 28, in <module>
    config = yaml.safe_load(open("config.yml"))
IOError: [Errno 2] No such file or directory: 'config.yml'

As I understand it, Python is looking for the config.yml file in the current directory (/home/kurt/dev/clones/ipercron-compose/controller) whereas I want it to look in the directory the module was imported from (/home/kurt/dev/clones/ipercron-utils/tester). Is there any way to specify this?

Upvotes: 2

Views: 2215

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140196

__file__ always contains the current module filepath (here /home/kurt/dev/clones/ipercron-utils/tester/tester.py).

Just perform a dirname on it => you have the path which contains your yml configuration file.

code it like this in your tester.py module (import os if not already done):

module_dir = os.path.dirname(__file__)
config = yaml.safe_load(open(os.path.join(module_dir,"config.yml")))

side note: __file__ doesn't work on the main file when the code is "compiled" using py2exe. In that case you have to do:

module_dir = os.path.dirname(sys.executable)

Upvotes: 2

Related Questions