day5-configparser
configparser模块
1. 配置文件格式
1 [DEFALUT] 2 compressionlevel = 9 3 serveraliveinterval = 45 4 compression = yes 5 forwardx11 = yes 6 7 [bitbucket.org] 8 user = hg 9 10 [topsecret.server.com] 11 host port = 50022 12 forwardx11 = no
2. 生成配置文件
1 # Python3 2 import configparser 3 4 # 创建对象 5 config = configparser.ConfigParser() 6 7 config["DEFAULT"] = {'ServerAliveInterval': '45', 8 'Compression': 'yes', 9 'CompressionLevel': '9'} 10 11 # 第一个组 12 config['bitbucket.org'] = {} 13 config['bitbucket.org']['User'] = 'hg' 14 15 # 第二个组 16 config['topsecret.server.com'] = {} 17 config['topsecret.server.com'] 18 config['topsecret.server.com']['Host Port'] = '50022' 19 config['topsecret.server.com']['ForwardX11'] = 'no' 20 21 # 配置DEFAULT 22 config['DEFAULT']['ForwardX11'] = 'yes' 23 24 # 写入文件 25 with open('example.ini', 'w') as configfile: 26 config.write(configfile)
3. 配置文件操作
1 import configparser 2 3 conf = configparser.ConfigParser() 4 # 读取配置文件 5 conf.read("example.ini") 6 7 print('-'*30) 8 # 配置组 9 print(conf.sections()) 10 # 默认配置组 11 print(conf.defaults()) 12 13 print('-'*30) 14 # 判断组名是否存在 15 group_flag = 1 if 'bitbucket.org' in conf else 0 16 print(group_flag) 17 18 print('-'*30) 19 # 取值 20 print(conf['bitbucket.org']['user']) 21 print(conf.get('bitbucket.org', 'user')) 22 23 print('-'*30) 24 # 循环取值 25 for key in conf['bitbucket.org']: 26 print(key) 27 # 以列表的形式返回bitbucket.org组和默认组的key值 28 print(conf.options('bitbucket.org')) 29 # 以字典的形式返回bitbucket.org组和默认组的key,value值 30 print(conf.items('bitbucket.org')) 31 32 print('-'*30) 33 # 删除section和option 34 conf.remove_section('bitbucket.org') 35 conf.remove_option('topsecret.server.com', 'forwardx11') 36 37 # 判断是否有某个section 38 print(conf.has_section("test")) 39 # 添加section 40 conf.add_section("test") 41 42 # 判断topsecret.server.com是否有ip值 43 print(conf.has_option("topsecret.server.com", "ip")) 44 # 设置ip值 45 conf.set("topsecret.server.com", "ip", "127.0.0.1") 46 47 # 将修改重新写入文件 48 # 可以写入新文件 49 with open("example.ini", "w") as f: 50 conf.write(f)

浙公网安备 33010602011771号