configparser模块
configparser模块用于处理特定格式的文件,本质上是利用open来操作文件。
#!/usr/bin/env python # coding=utf-8 import configparser config = configparser.ConfigParser() config.read('conf.conf', encoding='utf-8') ret = config.sections() # 获取所有节点名 ret = config.items('section1') # 获取section1 的键值对 ret = config.options('section1') # 获取section1的所有键 ret = config.get('section1', 'k3') # 获取section1某一键的值 # ret = config.getint('section1', 'k1') # 获取section1键k1的值并转换为int类型, 类型有getfloat, getboolean print(ret) # 检测节点 has_sec = config.has_section('section1') print(has_sec) # 添加节点 # config.add_section('section4') # config.write(open('conf.conf', 'w')) # 删除节点 config.remove_section('section2') config.write(open('conf.conf', 'w')) # 检测指定节点的键值对 has_opt = config.has_option('section1', 'k1') print(has_opt) # 删除指定节点的键值对 #config.remove_option('section1', 'k1') #config.write(open('conf.conf', 'w')) # 添加指定节点的键值对 config.set('section1', 'k1', '111') config.write(open('conf.conf', 'w'))