2.2 Adding Files

The add_file() method of ConfigParser is used to add configuration files to the parser. It returns an object which may be used for modifying option settings in the file and writing the changed file contents.

add_file( [cfgfile][,content][, type][, underkeys])

cfgfile is an optional keyword argument and is used to pass a file name string or a file stream. This argument defaults to None. See table below for details.

content is an optional keyword argument and is used to pass a file contents string or a file stream. This argument defaults to None. See table below for details.

type is an optional keyword argument used to control the parser used to read the configuration file. Argument may be set to either 'ini', 'py', or None (default). When set to None, file name extension is used to determine type. 'py' causes the file to be read (executed) as Python code otherwise the 'ini' syntax is assumed.

keys is an optional keyword argument. When omitted, None or an empty list, options read from this file will be read and stored using the sections as specified in the configuration file. Any keys passed in are used to extend the section names in the configuration file when the file is read and stored. Note, file is only read and parsed if keys used to obtain option settings contain all the keys in this list. See "Keys" (section 6) for more details.

The following table summarizes the legal combinations cfgfile and content arguments and the resulting file name and file contents utilized.

cfgfile content file name file contents
filename None cfgfile file is opened and read
stream None stream.name stream is read
filename stream cfgfile stream is read
None stream 'stream' stream is read
filename string cfgfile content
None string 'heredoc' content

The add_env_file() method of ConfigParser is used to read a configuration file specified by an environment variable and returns an object which may be used for modifying option settings in the file and writing the changed file contents. For ini configuration files the returned object is an instance of ConfigFileIni. If the environment variable does not exist, None will be returned.

add_env_file( var[,keys])

var is a required positional argument and is the name of the environment variable that contains the configuration filename to add. keys is an optional keyword argument. When omitted, None or an empty list, options read from this file will be read and stored using the sections as specified in the configuration file. Any keys passed in are used to extend the section names in the configuration file when the file is read and stored. Note, file is only read and parsed if keys used to obtain option settings contain all the keys in this list. See "Keys" (section 6) for more details.