[DEFAULT]
a = test
[mysql]
default-character-set=utf8
[mysqld]
datadir =/dbserver/data
port =33060
character-set-server=utf8
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
2、configparser 模块
configparser 模块的 ConfigParser 类来进行操作 ini 文件
可以将 section 当作 key, section 存储着键值对组成的字典,可以把 ini 文件当作一个嵌套的字典,默认使用的是有序字典
2.1 语法介绍
# Read and parse a filename or an iterable of filenames.
ConfigParser.read(self, filenames, encoding=None)# Return a list of section names, excluding [DEFAULT]
ConfigParser.sections(self)# Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.
ConfigParser.add_section(self, section)# Indicate whether the named section is present in the configuration.
ConfigParser.has_section(self, section)# Return a list of option names for the given section name.
ConfigParser.options(self, section)# Check for the existence of a given option in a given section.# If the specified `section' is None or an empty string, DEFAULT is assumed. If the specified `section' does not exist, returns False.
ConfigParser.has_option(self, section, option)# Get an option value for a given section.# If the key is not found and `fallback' is provided, it is used as a fallback value. `None' can be provided as a `fallback' value.
ConfigParser.get(
self,
section,
option,*,
raw=False,vars=None,
fallback=<objectobject at 0x000002E8694D1FF0>,)
ConfigParser.getint(
self,
section,
option,*,
raw=False,vars=None,
fallback=<objectobject at 0x000002E8694D1FF0>,**kwargs,)
ConfigParser.getfloat(
self,
section,
option,*,
raw=False,vars=None,
fallback=<objectobject at 0x000002E8694D1FF0>,**kwargs,)
ConfigParser.getboolean(
self,
section,
option,*,
raw=False,vars=None,
fallback=<objectobject at 0x000002E8694D1FF0>,**kwargs,)# Return a list of (name, value) tuples for each option in a section.
ConfigParser.items(
self,
section=<objectobject at 0x000002E8694D1FF0>,
raw=False,vars=None,)# Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.
ConfigParser.set(self, section, option, value=None)# Remove a file section.
ConfigParser.remove_section(self, section)# Remove an option.
ConfigParser.remove_option(self, section, option)# rite an .ini-format representation of the configuration state.
ConfigParser.write(self, fp, space_around_delimiters=True)
2.2 操作示例
In [339]:from configparser import ConfigParser
In [340]: cat test.ini
[DEFAULT]
a = test
[mysql]
default-character-set=utf8
[mysqld]
datadir =/dbserver/data
port =33060
character-set-server=utf8
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
In [341]:from configparser import ConfigParser
In [