Best way to retrieve variable values from a text file?

后端 未结 10 2192
再見小時候
再見小時候 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:30

    The other solutions posted here didn't work for me, because:

    • i just needed parameters from a file for a normal script
    • import * didn't work for me, as i need a way to override them by choosing another file
    • Just a file with a dict wasn't fine, as I needed comments in it.

    So I ended up using Configparser and globals().update()

    Test file:

    #File parametertest.cfg:
    [Settings]
    #Comments are no Problem
    test= True
    bla= False    #Here neither
    
    #that neither
    

    And that's my demo script:

    import ConfigParser
    
    cfg = ConfigParser.RawConfigParser()
    cfg.read('parametertest.cfg')       # Read file
    
    #print cfg.getboolean('Settings','bla') # Manual Way to acess them
    
    par=dict(cfg.items("Settings"))
    for p in par:
        par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments
    
    globals().update(par)  #Make them availible globally
    
    print bla
    

    It's just for a file with one section now, but that will be easy to adopt.

    Hope it will be helpful for someone :)

提交回复
热议问题