ConfigParser读写配置文件
ConfigParser简介
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
configparser模块支持读取.conf和.ini等类型的文件
[profile] name = Tom Smith age = 37 [spouse] name = Jane Smith age = 25 married = yes [children] name = Jimmy Smith gender = man
读取配置文件
使用ConfigParser 首选需要初始化实例,并读取配置文件
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import configparser config = configparser.ConfigParser() cf = config.read('new.ini',encoding='utf-8') # 读取文件名 print('cf:',cf)
cf: ['new.ini']
常用方法
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import configparser config = configparser.ConfigParser() cf = config.read('new.ini',encoding='utf-8') # 读取文件名 # print('cf:',cf) # 获取所用的section节点,以列表的形式返回 sections = config.sections() print('sections:',sections) # 获取指定section 的options,以列表的形式返回 options= config.options('spouse') print('options:',options) # 获取section下指定option的值 getint()转换为int型、getboolean()转换bool型、getfloat()转换为浮点型 name = config.get('children','name') gender = config.get('children','gender') print('name:',name) print('gender:',gender) # 获取指点section的所用配置信息 profile = config.items('profile') print('profile:',profile) # 修改某个option的值,如果不存在则会出创建 config.set('children','gender','woman') config.write(open('new.ini','w')) print('更改后:',config.get('children','gender')) config.set('children','gender','man') config.write(open('new.ini','w')) print('改回来:',config.get('children','gender')) # 检查section或option是否存在,bool值 bool_section = config.has_section('children') bool_option = config.has_option('children','gender') bool_false = config.has_option('children','first name') print('bool_section:',bool_section) print('bool_option:',bool_option) print('bool_false:',bool_false) # 添加section 和 option if not config.has_section('default'): config.add_section('default') if not config.has_option('default','family'): config.set('default','family','big house') config.write(open('new.ini','w')) print('default:',config.items('default')) # 删除section和 option config.remove_option('default','family') print('default:',config.items('default')) if not config.has_option('default','family'): config.set('default','family','big house') config.write(open('new.ini','w')) print('default:',config.items('default')) config.remove_section('default') # 删除default下所有信息 # 写入文件 config.write(open('new.ini','w')) print('sections:',config.sections())
sections: ['profile', 'spouse', 'children'] options: ['name', 'age', 'married'] name: Jimmy Smith gender: man profile: [('name', 'Tom Smith'), ('age', '37')] 更改后: woman 改回来: man bool_section: True bool_option: True bool_false: False default: [('family', 'big house')] default: [] default: [('family', 'big house')] sections: ['profile', 'spouse', 'children']