python configparser模块
1 import configparser 2 3 4 """ 5 sections() 返回所有的section 6 has_section(section) 判断是否有指定的section 7 has_option(section, option) 判断是否有指定的section中的option 8 options(section) 返回指定section中的所有option的列表 9 read(filenames, encoding=None) 给定文件名,读配置文件 10 read_file(f, filename=None) 给定文件描述符,读配置文件 11 read_string(string) 从字符串中读取配置文件 12 read_dict(dictionary) 从字典中读取配置文件 13 get(section, option, raw=False, vars=None, fallback=_UNSET) 读取指定的sention中的option内容,string 14 getint(section, options, raw=False, vars=None, fallback=_UNSET) 同get,结果转int 15 getfloat(section, options, raw=False, vars=None, fallback=_UNSET) 同get,结果转float 16 getboolean(section, options, raw=False, vars=None, fallback=_UNSET) 同get,结果转bool 17 items(section=_UNSET, raw=False, vars=None) 给section返回(name, value),否则(section_name, section_proxy) 18 remove_section(section) 删除section 19 remove_option(section, option) 删除指定section的option 20 set(section, option, value) 设置option 21 write(fp, space_around_delimiters=True) 写配置文件 22 """ 23 24 25 def write_config(filename): 26 config = configparser.ConfigParser() 27 # set db 28 section_name = 'db' 29 config.add_section(section_name) 30 config.set(section_name, 'dbname', 'MySQL') 31 config.set(section_name, 'host', '127.0.0.1') 32 config.set(section_name, 'port', '80') 33 config.set(section_name, 'password', '123456') 34 config.set(section_name, 'databasename', 'test') 35 36 # set app 37 section_name = 'app' 38 config.add_section(section_name) 39 config.set(section_name, 'loggerapp', '192.168.20.2') 40 config.set(section_name, 'reportapp', '192.168.20.3') 41 42 # write to file 43 with open(filename, 'a') as fd: 44 config.write(fd) 45 46 47 def update_config(filename, section, **kwargs): 48 config = configparser.ConfigParser() 49 config.read(filename) 50 # print(config.sections()) 51 for section in config.sections(): 52 print("[", section, "]") 53 items = config.items(section) 54 for item in items: 55 print("\t", item[0], " = ", item[1]) 56 if config.has_option("db", "dbname"): 57 config.set("db", "dbname", "11") 58 print("...............") 59 for key in kwargs: 60 print("\t", key, " = ", kwargs[key]) 61 if config.has_option(section, key): 62 config.set(section, key, kwargs[key]) 63 print("...............") 64 65 with open(filename, 'r+') as fd: 66 config.write(fd) 67 68 69 if __name__ == '__main__': 70 file_name = 'test.conf' 71 write_config(file_name) 72 update_config(file_name, 'app', reportapp='192.168.100.100')