Using ConfigParser to read a file without section name

前端 未结 7 2085
星月不相逢
星月不相逢 2020-11-27 03:36

I am using ConfigParser to read the runtime configuration of a script.

I would like to have the flexibility of not providing a section name (there are s

相关标签:
7条回答
  • 2020-11-27 04:08

    Enlightened by this answer by jterrace, I come up with this solution:

    1. Read entire file into a string
    2. Prefix with a default section name
    3. Use StringIO to mimic a file-like object
    ini_str = '[root]\n' + open(ini_path, 'r').read()
    ini_fp = StringIO.StringIO(ini_str)
    config = ConfigParser.RawConfigParser()
    config.readfp(ini_fp)
    


    EDIT for future googlers: As of Python 3.4+ readfp is deprecated, and StringIO is not needed anymore. Instead we can use read_string directly:

    with open('config_file') as f:
        file_content = '[dummy_section]\n' + f.read()
    
    config_parser = ConfigParser.RawConfigParser()
    config_parser.read_string(file_content)
    
    0 讨论(0)
提交回复
热议问题