标签:des style blog io ar color os sp on
#!/usr/bin/env python # -*-coding:utf-8 -*- __author__ = ‘shylock‘ import sys,os import ConfigParser def is_dir(config_path): return os.path.isdir(config_path) def read4Conf(config_path="./config",config_file=None,allow_no_value=False): if(is_dir(config_path)): config_path_file = config_path + os.sep + config_file cf = ConfigParser.ConfigParser(allow_no_value=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写配置项
标签:des style blog io ar color os sp on
原文地址:http://www.cnblogs.com/jachin/p/4119840.html