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?
1 Answer 1
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!
-
can you please explain the line name2decode = os.path.splitext(name2decode)[0]? What does splittext and [0] do?wookie– wookie09/25/2014 17:21:06Commented Sep 25, 2014 at 17:21
-
@wookie:
os.path.splitext()
splits a filename into a base and extension tuple, and[0]
selects just the base part. It gives you theimages
part ofimages.py
.Martijn Pieters– Martijn Pieters09/25/2014 17:28:59Commented Sep 25, 2014 at 17:28 -
Thank you. If I know the file extension of the file that I am seeking here, as an ex. "images.py" can i use name2decode = filename[:-3] which will drop the ".py" part and give the "images" part?wookie– wookie09/25/2014 17:58:25Commented Sep 25, 2014 at 17:58
-
1@wookie: if you know for certain that it'll always be those 3 characters, sure.Martijn Pieters– Martijn Pieters09/25/2014 18:15:01Commented Sep 25, 2014 at 18:15
name2decode = images.py
- shouldn't that bename2decode = "images.py"
? What does "does not work" mean - if an error, provide the full traceback.