后台系统免费模板网站,查看wordpress栏目id,贵州高端网站开发,网站信息建设总结1.configparser模块简介使用配置文件来灵活的配置一些参数是一件很常见的事情#xff0c;配置文件的解析并不复杂#xff0c;在python里更是如此#xff0c;在官方发布的库中就包含有做这件事情的库#xff0c;那就是configParserconfigParser解析的配置文件的格式比较象in…1.configparser模块简介使用配置文件来灵活的配置一些参数是一件很常见的事情配置文件的解析并不复杂在python里更是如此在官方发布的库中就包含有做这件事情的库那就是configParserconfigParser解析的配置文件的格式比较象ini的配置文件格式就是文件中由多个section构成每个section下又有多个配置项2.看一下configparser生成的配置文件的格式ini配置文件格式如下这里是注释[log]log_path base_dir/OutPut/log/[image]img_path base_dir/OutPut/image/[report]report_path base_dir/OutPut/report/[test_case]test_case_path base_dir/TestData/case.xlsx3.读取文件内容import configparserimport osimport sysBASE_DIR os.path.dirname(os.path.dirname(os.path.dirname(__file__)))if sys.platform win32:ENV_CONF_DIR os.path.join(BASE_DIR, Common/conf/env_config.ini).replace(/, \\)else:ENV_CONF_DIR os.path.join(BASE_DIR, Common/conf/env_config.ini)class Config(object):def __init__(self, path):self.path path #配置文件名self.cf configparser.ConfigParser() #创建一个配置文件对象self.cf.read(self.path, encodingutf-8) # 调用配置文件对象的读取方法并传入一个配置文件名def get(self, field, key): # 获取字符串类型的选项值result try:result self.cf.get(field, key)except:result return resultdef set(self, field, key, value):try:self.cf.set(field, key, value)self.cf.write(open(self.path, w))#创建一个配置文件并将获取到的配置信息使用配置文件对象的写入方法进行写入except:return Falsereturn Truedef r_config(config_file_path, field, key):rf configparser.ConfigParser()try:rf.read(config_file_path, encodingutf-8)if sys.platform win32:result rf.get(field, key).replace(base_dir, str(BASE_DIR)).replace(/, \\)else:result rf.get(field, key).replace(base_dir, str(BASE_DIR))except:sys.exit(1)return resultdef w_config(config_file_path, field, key, value):wf configparser.ConfigParser()try:wf.read(config_file_path)wf.set(field, key, value)wf.write(open(config_file_path, w))except:sys.exit(1)return Trueif __name__ __main__:print(r_config(ENV_CONF_DIR, log, log_path))print(r_config(ENV_CONF_DIR, DB, database))以上就是本文的全部内容希望对大家的学习有所帮助也希望大家多多支持我们。本文标题: Python configparser模块封装及构造配置文件本文地址: http://www.cppcns.com/jiaoben/python/331696.html