简介
想写一个登录注册的demo,但是以前的demo数据都写在程序里面,每一关掉程序新数据就没保存住。当然也可以写到文件里,然后再自己写一个读取、存储的办法,但是先看看有没有好轮子,查了一下真的有 - configparser
Note The ConfigParser module has been renamed to configparser in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
需要注意的是在 py2 中,该模块叫 ConfigParser,在 py3 中把字母全变成了小写。本文以 py3 为例
configparser
数据格式
下面的 config.ini 展示了配置文件的数据格式,用中括号[]括起来的为一个 section 例如 Default、Color;每一个 section 有多个 option,例如 serveraliveinterval、compression 等。option就是我们用来保存自己数据的地方,类似于键值对 optionname = value 或者是 optionname : value (也可以额外设置允许空值)
[Default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
values like this: 1000000
or this: 3.14159265359
[No Values]
key_without_value
empty string value here =
# 自定义颜色
[Color]
isset = true
version = 1.1.0
orange = 150,100,100
lightgreen = 0,220,0
数据类型
在configparser 保存的数据中,value 的值都保存为字符串类型,需要自己转换为自己需要的数据类型
Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own:
例如
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
属性和方法
从 init 中可以知道默认不允许值为空、键值对之间用 = 或 : 来表示等值、注释前缀是井号或者分号、默认键值对后面无注释。也就是说注释尽量不要一行里写了键值对又写注释。
ConfigParser 类的属性和方法
ConfigParser -- responsible for parsing a list of
configuration files, and managing the parsed database.
methods:
__init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
delimiters=('=', ':'), comment_prefixes=('#', ';'),
inline_comment_prefixes=None, strict=True,
empty_lines_in_values=True, default_section='DEFAULT',
interpolation=<unset>, converters=<unset>):
Create the parser. When `defaults' is given, it is initialized into the
dictionary or intrinsic defaults. The keys must be strings, the values
must be appropriate for %()s string interpolation.
When `dict_type' is given, it will be used to create the dictionary
objects for the list of sections, for the options within a section, and
for the default values.
When `delimiters' is given, it will be used as the set of substrings
that divide keys from values.
When `comment_prefixes' is given, it will be used as the set of
substrings that prefix comments in empty lines. Comments can be
indented.
When `inline_comment_prefixes' is given, it will be used as the set of
substrings that prefix comments in non-empty lines.
When `strict` is True, the parser won't allow for any section or option
duplicates while reading from a single source (file, string or
dictionary). Default is True.
When `empty_lines_in_values' is False (default: True), each empty line
marks the end of an option. Otherwise, internal empty lines of
a multiline option are kept as part of the value.
When `allow_no_value' is True (default: False), options without
values are accepted; the value presented for these is None.
When `default_section' is given, the name of the special section is
named