python中用来读取配置文件,配置文件的格式相同于windows下的ini配置文件
一、常用函数
read(filename) #读取配置文件,直接读取ini文件内容 sections() #获取ini文件内所有的section,以列表形式返回['logging', 'mysql'] options(sections) #获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password'] items(sections) #获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')] get(section, option) #获取section中option的值,返回为string类型 >>>>>获取指定的section下的option <class 'str'> 127.0.0.1 getint(section,option) 返回int类型 getfloat(section, option) 返回float类型 getboolean(section,option) 返回boolen类型
举例如下:
配置文件ini如下:
[logging] level = 20 path = server = [mysql] host=127.0.0.1 port=3306 user=root password=123456
代码如下:
import configparser from until.file_system import get_init_path conf = configparser.ConfigParser() file_path = get_init_path() print('file_path :',file_path) conf.read(file_path) sections = conf.sections() print('获取配置文件所有的section', sections) options = conf.options('mysql') print('获取指定section下所有option', options) items = conf.items('mysql') print('获取指定section下所有的键值对', items) value = conf.get('mysql', 'host') print('获取指定的section下的option', type(value), value)
综合使用方法:
import configparser """ 读取配置文件信息 """ class ConfigParser(): config_dic = {} @classmethod def get_config(cls, sector, item): value = None try: value = cls.config_dic[sector][item] except KeyError: cf = configparser.ConfigParser() cf.read('settings.ini', encoding='utf8') #注意setting.ini配置文件的路径 value = cf.get(sector, item) cls.config_dic = value finally: return value if __name__ == '__main__': con = ConfigParser() res = con.get_config('logging', 'level') print(res)
二、设置某个option 的值
conf.set("topsecret.server.com","port","67000") #修改port的值 conf.write(open("config_parser","w")) #u将修改的内容回写到文件上
三、添加一个section
conf.add_section('liuqing') conf.set('liuqing', 'int', '15') conf.set('liuqing', 'bool', 'true') conf.set('liuqing', 'float', '3.1415') conf.write(open("config_parser","w"))
四、
. 移除section 或者option 。(只要进行了修改就要写回的哦)
1 conf.remove__option('liuqing','int') 2 conf.remove_section('liuqing') 3 conf.write(open("test.conf", "w"))