configparser用于处理特定格式的文件,其本质上是利用open来操作文件。
# 注释1 ; 注释2 [section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [section2] # 节点 k1 = v1 # 值 指定格式
生成.ini
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval':'45', 'Compression':'yes', 'CompressionLevel':'9' } config['bitbucket.org'] = { } config['bitbucket.org']['User'] = 'abc' config['topsecret.server.com'] = { } topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' topsecret['ForwardX11'] = 'no' config["DEFAULT"]['ForwardX11'] = 'yes' with open('example.ini','w') as configfile: config.write(configfile)
[DEFAULT] compression = yes serveraliveinterval = 45 compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = abc [topsecret.server.com] host port = 50022 forwardx11 = no
读取
import configparser config = configparser.ConfigParser() config.read('example.ini') # 查看所有标题 res = config.sections() print(res) # ['bitbucket.org', 'topsecret.server.com'] # 查看标题section下所有的key=value的key ,DEFAULT 的key会在每一个子项中出现 options = config.options('bitbucket.org') print(options) # ['user', 'passwd', 'compression', 'serveraliveinterval', 'compressionlevel', 'forwardx11'] # 查看标题section1下所有key=value的(key,value)格式 item_list=config.items('bitbucket.org') print(item_list) # [('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'abc'), ('passwd', '123')] # 查看标题section1下user的值=>字符串格式 val = config.get('bitbucket.org','user') print(val) # abc # 查看标题section1下passwd的值=>整数格式 val1 = config.getint('bitbucket.org','passwd') print(val1) # 123 # 查看标题section1下is_admin的值=>布尔值格式 val2=config.getboolean('bitbucket.org','is_admin') print(val2) # True # 查看标题section1下salary的值=>浮点型格式 val3=config.getfloat('bitbucket.org','salary') print(val3) # 31.0