wookie
wookie

Reputation: 331

Importing a dictionary from a module which has its name in a variable

I wrote a program which encode all files inside a folder into strings and write it to a pyfile as a dictionary.

The name of the py file to be created is given along with the path, the dictionary is created by adding " = data" to its name. For instance:

pyfilename = "images.py"

then the dictionary with the images is written into this file as imagesdata.

Now I need to decode any py file previously encoded in this manner.

I give only the name of the py file in a variable and the program gets all other names from this and imports the correct dictionary from the correct module with the given name. Sample code given below.

name2decode = images.py
dictname = name2decode + "data"

the program should do

from name2decode import dictname

where name2decode and dictnames are variables. I tried using the __import__("name2decode.dictname") syntax but for some reason this does not work. Maybe I got the syntax wrong.

How can this be done?

Upvotes: 1

Views: 1733

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124090

Import the module name, then use getattr() to get the dictionary object from that:

import importlib
import os.path

name2decode = os.path.splitext(name2decode)[0]
module = importlib.import_module(name2decode)
dictionary = getattr(module, dictname)

Note that you need to remove the .py extension when importing!

Upvotes: 1

Related Questions