Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python importing a function with file's name contained in a variable

Tags:

python

import

Hi I have a directory in the same folder as my main script called 'actions' in this folder there are several scripts that may be used at any time by the main script. I am at the point where I have the name of the script in the form of a string in a variable called VAR (for the sake of example). I would like to be able to import this file using the variable.

like image 523
bs7280 Avatar asked Mar 27 '26 23:03

bs7280


2 Answers

If your aim is simply to execute the files, you can use

with open(filename) as f:
    exec(compile(f.read(), filename, "exec"))

or the Python 2.x function execfile().

If you actually want to import the modules using the full import machinery, you need an __init__.py in the directory actions, and can use something like

module = __import__("actions.foo")

to import actions/foo.py.

like image 69
Sven Marnach Avatar answered Mar 29 '26 13:03

Sven Marnach


Use the __import__ function

__import__(str)
like image 35
nims Avatar answered Mar 29 '26 12:03

nims



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!