python yaml dump_python yaml文件数据按原有的数据顺序dump

importosimportyamlclassYamlUtils():def __init__(self,folder_name='config'):

self.foler_name=folder_namedefget_yaml_load(self, file_name):

yaml_filename= self.__get_yaml_file(file_name)

f= open(yaml_filename, encoding='utf-8')

yaml_load=yaml.full_load(f)returnyaml_loaddef __get_yaml_file(self, file_name):""":param file_name: the filename of the configfile

:return: the objection of the config"""

try:

yaml_file= self.__get_file_path(self.foler_name, file_name)returnyaml_fileexceptException as e:print("read config file error:" +str(e))

@staticmethoddef __get_file_path(folder_name, file_name):""":param folder_name: the directory of the config ,the default directory is config

:param file_name: the filename of the configfile

:return: the objection of the config"""

try:

config_path= os.path.abspath('..')

folder_path=os.path.join(config_path, folder_name)

file_path=os.path.join(folder_path, file_name)returnfile_pathexceptException as e:print('read config file failed' +str(e))defset_yaml(self, file_name,content):"""调用此方法时,需新建一个YamlUtils().set_yaml(file_name,content)

用原来的设置不会生效

default_flow_style=False : 表示dump后的字典数据全部以yml格式显示,默认为为True

sort_keys=False : 表示dump后的字典数据按原有的顺序示,为True时按字母的排序展示,默认为为True"""yaml_filename= self.__get_yaml_file(file_name)

f= open(yaml_filename,'w', encoding='utf-8')

yaml_dump= yaml.dump(content,f,allow_unicode=True, default_flow_style=False,sort_keys=False)#print("数据更新完成")

return yaml_dump

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值