目标读写API解析数据结构简单易处理支持对象序列化/反序列化库比较好用的库是ruamel,需要安装:pipinstallruamel。yaml然后在代码中导入:fromruamel.yamlimportYAML但是导入的YAML是一个类。实际使用的时候,需要创建一个实例yaml=YAML()来读写文件,准备一个配置文件:id:100name:"Testproject"version:"3.1"steps:-id:18action:"Prepare”expects:-id:238,result:GOOD-id:239,result:PERFECT在阅读代码时,首先需要自己打开文件,然后将文件对象传给yamlexample:withopen(conf_file)asf:data=yaml.load(f)fork,vindata.items():cls.handle_value(data,k,v)conf=yaml.load(f)遍历这里加载后的结果再由业务功能(handle_value)。写入和读取代码类似,或者自己以写入方式打开文件,然后将一个dict/list嵌套结构的对象传递给dump函数withopen(conf_file,'w')asf:the_list=[]forstepinself.steps:the_list.append(step.to_dict())documents=yaml.dump(the_list,f)例子中最外层的对象是一个list,换成dict是没有问题的。简而言之,它需要是一个可枚举的内容对象。序列化/反序列化ruamel本身提供了序列化/反序列化支持:首先在需要序列化的类中添加一个yaml_tag类属性,加上yaml_object注解,在该类中添加to_yaml和from_yaml两个类作为序列化前缀方法,序列化和反序列化分别处理如下:@yaml_object(yaml)classScreenRect(dict):yaml_tag=u'!rect'def__init__(self,left:int=None,right:int=None,top:int=None,bottom:int=None):#super(ScreenRect,self).__init__([left,right,top,bottom])#self._inner_list=[left,right,top,bottom]self['l']=leftself['r']=rightself['']=topself['b']=bottom@propertydefleft(self):returnself['l']@propertydefright(self):returnself['r']@propertydeftop(self):returnself['t']@propertydefbottom(self):returnself['b']def__str__(self):return'l:{},r:{},t:{},b:{}'.format(self.left,self.right,self.top,self.bottom)@classmethoddefto_yaml(cls??,representer,node):返回代表。represent_scalar(cls.yaml_tag,'l:{},r:{},t:{},b:{}'.format(node.left,node.right,node.top,node.bottom))#return{'l':self.left,'r':self.right,'t':self.top,'b':self.bottom}@classmethoddeffrom_yaml(cls??,constructor,node):splits=node.value.split(',')#test=list(map(lambdax:x+'_sss',splits))v=list(map(lambdax:x[1],map(methodcaller("split",":"),splits)))#print(v)返回cls(left=int(v[0]),right=int(v[1]),top=int(v[2]),bottom=int(v[3]))上面的例子中,ScreenRect类是dict的子类,但是序列化的时候希望生成特定格式的字符串,所以封装在to_yaml中。几个属性的定义只是为了方便以后为ScreenRect类实例读写数据,并没有必要生成以后的数据,如下所示:rect:!rectl:1415,r:1805,t:239,b:609刚开始用汉字的时候发现utf-8编码的配置文件不能是我自己的代码有问题。打开文件时只需要指定编码:withopen(conf_file,encoding='utf-8')asf:
