reading dictionary's (key,value) from file
Jeffrey Froman
jeffrey at fro.man
Mon Apr 7 12:54:36 EDT 2008
ankitks.mital at gmail.com wrote:
> so this is what my option files look like:
>
> 1opt.txt
> { '-cc': '12',
> '-I': r'/my/path/work/'}
You can turn these strings read from text files into actual dictionaries
using eval:
>>> d = eval("{ '-cc': '12', '-I': r'/my/path/work/'}")
>>> d
{'-I': '/my/path/work/', '-cc': '12'}
>>> type(d)
<type 'dict'>
Note that eval will happily execute all sorts of arbitrary code, so this is
not a good solution if you don't fully trust your option file creators.
It's also a bit clunky compared to simply importing. Since you already have
dictionary-literal syntax in your text file, why not add a
left-hand-operator and make it a module instead? For example:
# opt1.py
d = { '-cc': '12',
'-I': r'/my/path/work/'}
# main.py
from opt1 import d
--
Jeffrey
More information about the Python-list
mailing list