1 #__author__: Administrator 2 #__date__: 2018/8/8 3 # configparse 生成配置文件,配置文会以件.ini结尾 4 # 对于格式有要求 5 # 创建配置文档 6 import configparser 7 config = configparser.ConfigParser() 8 config["DEFAULT"] = {'ServerAliveInterval': '45', 9 'Compression': 'yes', 10 'CompressionLevel': '9', 11 'ForwardX11':'yes' 12 } 13 config['bitbucket.org'] = {'User':'hg'} 14 15 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} 16 17 with open('example.ini', 'w') as f: 18 config.write(f) 19 20 21 # import configparser 22 # config = configparser.ConfigParser() 23 #---------------------------查找文件内容,基于字典的形式 24 # print(config.sections()) # [] 读组信息,但是没有指定到底读哪个文件,尽管不报错,但是读出来是空 25 26 # config.read('example.ini') # 选取要读取的文件 27 # print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] [DEFAULT]会不显示 28 29 # print('bytebong.com' in config) # False 判断组在不在文件里面 30 # print('bitbucket.org' in config) # True 31 # 32 # print(config['bitbucket.org']["user"]) # hg 查找文件的组内的某个项的内容 33 # print(config['DEFAULT']['Compression']) # yes [DEFAULT]里面也是可以拿出来的 34 # print(config['topsecret.server.com']['ForwardX11']) # no 35 # 36 # print(config['bitbucket.org']) #<Section: bitbucket.org> 打印出来地址,没什么用 37 # 38 # for key in config['bitbucket.org']: # 注意,有default会默认default的键 39 # print(key) 40 # 41 # print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 42 # 43 # print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对 44 # 45 # print(config.get('bitbucket.org','compression')) # yes get方法Section下的key对应的value 46 47 # 增加更改删除 48 # import configparser 49 # config = configparser.ConfigParser() 50 # config.read('example.ini') # 读文件 51 # config.add_section('yuan') # 增加section 52 # config.remove_section('bitbucket.org') # 删除一个section 53 # config.remove_option('topsecret.server.com',"forwardx11") # 删除一个配置项 54 # config.set('topsecret.server.com','k1','11111') 55 # config.set('yuan','k2','22222') 56 # f = open('new2.ini', "w") 57 # config.write(f) # 写进文件 58 # f.close()
1 [DEFAULT] 2 serveraliveinterval = 45 3 compression = yes 4 compressionlevel = 9 5 forwardx11 = yes 6 7 [bitbucket.org] 8 user = hg 9 10 [topsecret.server.com] 11 host port = 50022 12 forwardx11 = no