RYS221
RYS221

Reputation: 50

Dynamically import files from another directory

My input is a list of file names (as a list of variables) and I know the path to these files. Each file has a function called "test" and I have to call the "test" function from each of these files. The path is not my working directory. I need to be able to dynamically import these files.

I tried using importlib, but I get the following errors:

import importlib

importlib.import_module("..\..\foo", package=None)
TypeError: the 'package' argument is required to perform a relative import for '..\\..\\x0coo'
importlib.import_module("C:\Users\Desktop\foo", package=None)
ModuleNotFoundError: No module named 'C:\\Users\\Desktop\\foo'

How would I go about executing the function in a file, using the filename and path (both stored in variables)?

Upvotes: 0

Views: 1355

Answers (2)

electrogas
electrogas

Reputation: 276

I'm not sure this is the best way, but I solved this by first adding the path to the module to sys.path:

>>import sys
>>sys.path.append('/path/to/module')
>>mod=importlib.import_module('my_module_name')

then you can call functions in that module like this

>>mod.myfunc(myargs)

or, if you have the function name in a python string like func='myfunctionname' you can call it like

>>mod.__dict__[func](args)

Upvotes: 1

ab123
ab123

Reputation: 357

I'd need to see more code, but my first guess is that you need to replace \ with / in your Directory string, since \ escapes out of the string.

Upvotes: 0

Related Questions