首页 > 代码库 > Python ConfigParser 读取配置向 SafeConfigParser写配置项
Python ConfigParser 读取配置向 SafeConfigParser写配置项
#!/usr/bin/env python# -*-coding:utf-8 -*-__author__ = ‘shylock‘import sys,osimport ConfigParserdef is_dir(config_path): return os.path.isdir(config_path)def read4Conf(config_path="./config",config_file=None,allow_no_value=http://www.mamicode.com/False): if(is_dir(config_path)): config_path_file = config_path + os.sep + config_file cf = ConfigParser.ConfigParser(allow_no_value=http://www.mamicode.com/allow_no_value) try: cf.readfp(open(config_path_file)) except IOError,e: print("%s file not in %s dir" %(config_path,config_file)) exit(1) else: cf.read(config_path_file) return cf else: print "%s is not a dir" %config_path exit(1)def write2Conf(config_path="./config",config_file=None): if(is_dir(config_path)): config_path_file = config_path + os.path.sep + config_file scf = ConfigParser.SafeConfigParser() try: scf.readfp(open(config_path_file)) except IOError,e: print("%s file not in %s dir" %(config_path,config_file)) exit(1) else: scf.read(config_path_file) return scf,config_path_file else: print "%s is not a dir" %config_path exit(1)if __name__ == "__main__": dir="/Users/shyker/Desktop/Scripts/" file="init.conf" #cf = read4Conf(dir,file,True) #print cf.sections() #print cf.options("baseconf") #print cf.get("baseconf",‘host‘) #print cf.getint("baseconf",‘port‘) #print cf.get(‘baseconf‘,‘password‘) scf,config_path_file = write2Conf(dir,file) scf.set("baseconf",‘password‘,‘12345‘) #value 必须为unicode或者str with open(config_path_file,"w") as configFile: scf.write(configFile)
Python ConfigParser 读取配置向 SafeConfigParser写配置项
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。