1

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?

jonrsharpe
123k30 gold badges273 silver badges483 bronze badges
asked Sep 25, 2014 at 9:36
1
  • 1
    name2decode = images.py - shouldn't that be name2decode = "images.py"? What does "does not work" mean - if an error, provide the full traceback. Commented Sep 25, 2014 at 9:38

1 Answer 1

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!

answered Sep 25, 2014 at 9:38
4
  • can you please explain the line name2decode = os.path.splitext(name2decode)[0]? What does splittext and [0] do? Commented 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 the images part of images.py. Commented 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? Commented Sep 25, 2014 at 17:58
  • 1
    @wookie: if you know for certain that it'll always be those 3 characters, sure. Commented Sep 25, 2014 at 18:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.