Using ConfigParser to read a file without section name

前端 未结 7 2185
星月不相逢
星月不相逢 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 03:55

    You can do this in a single line of code.

    In python 3, prepend a fake section header to your config file data, and pass it to read_string().

    from configparser import ConfigParser
    
    parser = ConfigParser()
    with open("foo.conf") as stream:
        parser.read_string("[top]\n" + stream.read())  # This line does the trick.
    

    You could also use itertools.chain() to simulate a section header for read_file(). This might be more memory-efficient than the above approach, which might be helpful if you have large config files in a constrained runtime environment.

    from configparser import ConfigParser
    from itertools import chain
    
    parser = ConfigParser()
    with open("foo.conf") as lines:
        lines = chain(("[top]",), lines)  # This line does the trick.
        parser.read_file(lines)
    

    In python 2, prepend a fake section header to your config file data, wrap the result in a StringIO object, and pass it to readfp().

    from ConfigParser import ConfigParser
    from StringIO import StringIO
    
    parser = ConfigParser()
    with open("foo.conf") as stream:
        stream = StringIO("[top]\n" + stream.read())  # This line does the trick.
        parser.readfp(stream)
    

    With any of these approaches, your config settings will be available in parser.items('top').

    You could use StringIO in python 3 as well, perhaps for compatibility with both old and new python interpreters, but note that it now lives in the io package and readfp() is now deprecated.

    Alternatively, you might consider using a TOML parser instead of ConfigParser.

提交回复
热议问题