python读写配置文件ConfigParser
2017-11-18 00:03
435 查看
# -* - coding: UTF-8 -* -
import ConfigParser
#生成config对象
conf = ConfigParser.ConfigParser()
#用config对象读取配置文件
conf.read("test.cfg")
#以列表形式返回所有的section
sections = conf.sections()
print 'sections:', sections #sections: ['sec_b', 'sec_a']
#得到指定section的所有option
options = conf.options("sec_a")
print 'options:', options #options: ['a_key1', 'a_key2']
#得到指定section的所有键值对
kvs = conf.items("sec_a")
print 'sec_a:', kvs #sec_a: [('a_key1', '20'), ('a_key2', '10')]
#指定section,option读取值
str_val = conf.get("sec_a", "a_key1")
int_val = conf.getint("sec_a", "a_key2")
print "value for sec_a's a_key1:", str_val #value for sec_a's a_key1: 20
print "value for sec_a's a_key2:", int_val #value for sec_a's a_key2: 10
#写配置文件
#更新指定section,option的值
conf.set("sec_b", "b_key3", "new-$r")
#写入指定section增加新option和值
conf.set("sec_b", "b_newkey", "new-value")
#增加新的section
conf.add_section('a_new_section')
conf.set('a_new_section', 'new_key', 'new_value')
#写回配置文件
conf.write(open("test.cfg", "w"))
import ConfigParser
#生成config对象
conf = ConfigParser.ConfigParser()
#用config对象读取配置文件
conf.read("test.cfg")
#以列表形式返回所有的section
sections = conf.sections()
print 'sections:', sections #sections: ['sec_b', 'sec_a']
#得到指定section的所有option
options = conf.options("sec_a")
print 'options:', options #options: ['a_key1', 'a_key2']
#得到指定section的所有键值对
kvs = conf.items("sec_a")
print 'sec_a:', kvs #sec_a: [('a_key1', '20'), ('a_key2', '10')]
#指定section,option读取值
str_val = conf.get("sec_a", "a_key1")
int_val = conf.getint("sec_a", "a_key2")
print "value for sec_a's a_key1:", str_val #value for sec_a's a_key1: 20
print "value for sec_a's a_key2:", int_val #value for sec_a's a_key2: 10
#写配置文件
#更新指定section,option的值
conf.set("sec_b", "b_key3", "new-$r")
#写入指定section增加新option和值
conf.set("sec_b", "b_newkey", "new-value")
#增加新的section
conf.add_section('a_new_section')
conf.set('a_new_section', 'new_key', 'new_value')
#写回配置文件
conf.write(open("test.cfg", "w"))
相关文章推荐
- Python自动化测试 (二) ConfigParser模块读写配置文件
- 【python】configparser读写配置文件
- python--ConfigParser读写改配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python自动化测试 -ConfigParser模块读写配置文件
- python3 configparser对配置文件读写
- Python模块之ConfigParser - 读写配置文件
- Python使用自带的ConfigParser模块读写ini配置文件
- Python模块之ConfigParser - 读写配置文件
- Python自动化测试 (二) ConfigParser模块读写配置文件
- Python - ConfigParser模块读写配置文件
- Python模块之ConfigParser - 读写配置文件
- Python模块之ConfigParser - 读写配置文件
- 用ConfigParser模块读写配置文件——Python
- Python模块学习之ConfigParser读写配置信息
- Python自动化测试 (二) ConfigParser模块读写配置文件
- python学习笔记之编写readConfig读写配置文件
- python模块之ConfigParser:解析配置文件模块
- Python之配置文件模块 ConfigParser
- python ConfigParser 配置读写