欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python?yaml文件數(shù)據(jù)按原有的數(shù)據(jù)順序dump問題小結(jié)

 更新時間:2023年11月01日 10:04:17   作者:pandaly  
這篇文章主要介紹了python?yaml文件數(shù)據(jù)按原有的數(shù)據(jù)順序dump,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧

yml文件的更新后工具類:

import os
import yaml
class YamlUtils():
    def __init__(self,folder_name='config'):
        self.foler_name = folder_name
    def get_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)
        return yaml_load  def __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)
            return yaml_file
        except Exception as e:
            print("read config file error:" + str(e))
    @staticmethod
    def __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)
            return file_path
        except Exception as e:
            print('read config file failed ' + str(e))
    def set_yaml(self, file_name,content):
        """
        調(diào)用此方法時,需新建一個YamlUtils().set_yaml(file_name,content)
        用原來的設(shè)置不會生效
        default_flow_style=False : 表示dump后的字典數(shù)據(jù)全部以yml格式顯示,默認(rèn)為為True
        sort_keys=False : 表示dump后的字典數(shù)據(jù)按原有的順序示,為True時按字母的排序展示,默認(rèn)為為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("數(shù)據(jù)更新完成")
        return yaml_dump

yml文件原有數(shù)據(jù)順序:

更改字段值后的順序:

出現(xiàn)原因是:

yaml.dump(content,f,allow_unicode=True, default_flow_style=False,sort_keys=True)
該行的代碼中sort_keys的默認(rèn)值為True,改為Flase后可修復(fù)代順序變化的問題

到此這篇關(guān)于python yaml文件數(shù)據(jù)按原有的數(shù)據(jù)順序dump的文章就介紹到這了,更多相關(guān)python yaml文件dump內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論