1 import configparser 2 3 # config = configparser.ConfigParser() 4 # config["DEFAULT"] = {'Port':3306, 5 # 'Server_name':'localhost', 6 # 'Server_ip':'127.0.0.1'} 7 # config["USER"] = {'user':'root', 8 # 'password':123456, 9 # 'name':'root'} 10 # with open('web_config','w') as f: 11 # config.write(f) 12 # config2 = configparser.ConfigParser() 13 # config2.read('web_config') 14 # print(config2.sections()) # "DEFAULT默认不显示" 15 # # ['USER', 'LOG'] 16 # print('PASS' in config2) # False 判断节是否在配置文件里面 17 # # False 18 # print(config2['USER']['user']) # 打印节点下面的配置 19 # # root 20 # for key in config2['USER']: # 打印某节下下面的所有配置项,DEFAULT配置也会打印出来 21 # print(key) 22 # user 23 # password 24 # name 25 # port 26 # server_name 27 # server_ip 28 # print(config2.items('USER')) # 打印键值对,DEFAULE也会被打印 29 # [('port', '3306'), ('server_name', 'localhost'), ('server_ip', '127.0.0.1'), ('user', 'root'), 30 # print(config2.get('USER','user')) # 通过get方法去取值 31 32 # 配置文件的增删改 33 # config3 = configparser.ConfigParser() 34 # config3.read('web_config') 35 # 36 # config3.add_section('MOUNT') # 增加配置节点 37 # config3.remove_section('LOG') # 删除配置节点 38 # 39 # config3.remove_option('USER','root') # 删除某个节点配置 40 # config3.set('USER','password','111') # 修改某个具体配置项 41 # config3.set('MOUNT','mount','mnt') 42 # 43 # with open('web_config','w') as f: 44 # config3.write(f)