Best way to retrieve variable values from a text file?

后端 未结 10 2216
再見小時候
再見小時候 2020-11-30 19:44

Referring on this question, I have a similar -but not the same- problem..

On my way, I\'ll have some text file, structured like:

var_a: \'home\'
var_         


        
10条回答
  •  没有蜡笔的小新
    2020-11-30 20:29

    Load your file with JSON or PyYAML into a dictionary the_dict (see doc for JSON or PyYAML for this step, both can store data type) and add the dictionary to your globals dictionary, e.g. using globals().update(the_dict).

    If you want it in a local dictionary instead (e.g. inside a function), you can do it like this:

    for (n, v) in the_dict.items():
        exec('%s=%s' % (n, repr(v)))
    

    as long as it is safe to use exec. If not, you can use the dictionary directly.

提交回复
热议问题