阿小信大人的头像
Talk is cheap. Show me the code. Linus Torvalds

PyYAML有序更新yaml文件2017-05-04 16:07

yaml默认load进来是个字典,所以无法保持原本的顺序,要想不改变原本的yaml结构更新yaml文件内容需要用到以下方法

from collections import OrderedDict
import yaml

def ordered_yaml_load(yaml_path, Loader=yaml.Loader,
                    object_pairs_hook=OrderedDict):
    class OrderedLoader(Loader):
        pass

    def construct_mapping(loader, node):
        loader.flatten_mapping(node)
        return object_pairs_hook(loader.construct_pairs(node))
    OrderedLoader.add_constructor(
        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
        construct_mapping)
    with open(yaml_path) as stream:
        return yaml.load(stream, OrderedLoader)


def ordered_yaml_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
    class OrderedDumper(Dumper):
        pass

    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())
    OrderedDumper.add_representer(OrderedDict, _dict_representer)
    return yaml.dump(data, stream, OrderedDumper, **kwds)

# load yaml file
yaml_dict = ordered_yaml_load(yaml_file_path)

# dump new yaml file
with open(yaml_file_path, 'w') as f:
    ordered_yaml_dump(new_yaml_dict, f, default_flow_style=False)

如果您觉得从我的分享中得到了帮助,并且希望我的博客持续发展下去,请点击支付宝捐赠,谢谢!

若非特别声明,文章均为阿小信的个人笔记,转载请注明出处。文章如有侵权内容,请联系我,我会及时删除。

#Python#  
分享到:
阅读[1049] 评论[1]

你可能也感兴趣的文章推荐

本文最近访客

发表评论

#1 网友199.*.*.81[加拿大]70904 :
test
2018-03-22 17:04 回复