""""[ ]" 包含的为 section,section 下面为类似于 key - value 的配置内容;
configparser 默认支持 '=' ':' 两种分隔.
ConfigParser 模块在 python3 中修改为 configparser. 这个模块定义了一个 ConfigParser 类,
该类的作用是使用配置文件生效, 配置文件的格式和 windows 的 INI 文件的格式相同. conf
- """
- # 初始化实例
- config = configparser.ConfigParser() #注意大小写
- # 先要读取配置文件
- config.read("test.ini")
- # 获取所有的 sections
- config.sections() # 返回值为列表 ['test1', 'test2', 'test3'] , 会过滤掉 ["DEFAULT"]
- # 获取指定 section 的 key value (注意 key 会全部变为小写, 而 value 不会)
- config.items('test1') # [('money', '100'), ('name', 'WangFuGui'), ('age', '20')]
- # 获取指定 section 的 keys name 变为小写
- config.options("test1") # ['name', 'age', 'money']
- # 获取指定的 key 的 value name 大小写均可以 value 默认为字符
- config["test1"]["Name"] # WangFuGui
- config.get("test1","name") # WangFuGui
- config.getint("test1","age") # 100 转换为 int 类型
- # 检查
- "DEFAULT" in config # True
- "100"in config["test1"]["money"] # True
- # 添加
- if "add_section1" not in config:
- config.add_section("add_section1")
- config.set("add_section1","hobby","game") #用 set 方法
- config.write(open("test.ini","w")) # 一定要写入才生效
- # 移除
- config.remove_option("add_section1","hobby")
- config.remove_section("add_section1")
- config.write(open('test.ini',"w")) # 一定要写入才生效
来源: http://www.bubuko.com/infodetail-2621931.html