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')
相關文章
相關標籤/搜索