python常用模块-配置文档模块(configparser)
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
ConfigParser模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。类似于apache和mysql的配置文件就用这个模块生成的。
一.创建配置文件
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:y1053419035@qq.com 6 7 8 """ 9 该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值) 10 """ 11 12 import configparser 13 14 cfg = configparser.ConfigParser() #创建一个空字典,即“{}” 15 16 cfg["DEFAULT"] = { 17 "ServerAliveInterval" :110, 18 "Compression":"YES", 19 "CompressionLevel":15, 20 "ForwardX11":"YES", 21 } 22 23 cfg["User information"] = { 24 "USER":"Yinzhengjie", 25 } 26 27 cfg["yinzhengjie.org.cn"] = { 28 "Port":3389, 29 "ForwardX11":"no", 30 } 31 32 with open("cfg.ini","w")as f: 33 cfg.write(f)
1 [DEFAULT] 2 serveraliveinterval = 110 3 compression = YES 4 compressionlevel = 15 5 forwardx11 = YES 6 7 [User information] 8 user = Yinzhengjie 9 10 [yinzhengjie.org.cn] 11 port = 3389 12 forwardx11 = no