zoukankan      html  css  js  c++  java
  • ruamel.yaml 增删改查

    pip install ruamel.yaml

    读取:

    from ruamel.yaml import YAML
    from pathlib import Path
    
    # default, if not specfied, is 'rt' (round-trip)
    yaml = YAML(typ='safe')
    
    # 参数doc是 an object that has the .read() method, a string or a pathlib.Path()
    data = yaml.load(Path("test_out.yaml"))
    print(data)
    
    data2 = yaml.load("""a:
      b: 2
      c: 3
    """)
    print(data2)
    

    写入:

    from ruamel.yaml import YAML
    from pathlib import Path
    
    yaml = YAML()
    yaml.indent(mapping=2, sequence=4, offset=2)
    
    
    def tr(s):
        return s.replace('
    ', '<
    ')  # such output is not valid YAML!
    
    
    # 可以传入一个处理字符串的函数,来处理需要输出的yaml文件中的内容
    yaml.dump({'a': [1, 2]}, Path("test_out.yaml"), transform=tr)
    

    修改:

    a:
      - 1
      - 2
    b:
      name: jim
    
    from pathlib import Path
    import ruamel.yaml
    
    yaml = ruamel.yaml.YAML()
    yaml.indent(mapping=2, sequence=4, offset=2)
    
    data = yaml.load(Path("test_out.yaml"))
    
    # 新增
    data['a'].append({"b": 18})
    data['a'].append(18)
    
    # 给a中列表第一个值添加注释
    data['a'].yaml_add_eol_comment('comment 4', 0)  # takes column of comment 1
    # 给b中指定的字段添加注释
    data['b'].yaml_add_eol_comment('comment 5', 'name')  # takes column of comment 2
    #  column=10 指定注释的离行首的距离
    data['a'].yaml_add_eol_comment('comment 7', 1, column=10)
    
    yaml.dump(data, Path("test.yaml"))
    
    from ruamel.yaml import YAML
    from pathlib import Path
    
    yaml_str = """
    first_name: Art
    middle name:
      Vandelay: 18
    occupation: Architect  # This is an occupation comment
    about: Art Vandelay is a fictional character that George invents...
    """
    
    yaml = YAML()
    
    data = yaml.load(yaml_str)
    print(data)
    data.insert(1, 'last name', {'Vandelay': 18})
    yaml.indent(mapping=2, sequence=4, offset=2)
    yaml.dump(data, Path('test.yaml'))
    

    ---分隔

    a:
      - 1
      - 2
    b:
      name: jim
    
    ---
    c:
      - 1
      - 2
    
    from pathlib import Path
    import ruamel.yaml
    
    yaml = ruamel.yaml.YAML()
    yaml.indent(mapping=2, sequence=4, offset=2)
    
    data = yaml.load_all(Path("test_out.yaml"))
    
    print(list(data))
    
    
  • 相关阅读:
    实用硬件篇(一)
    iOS通讯录(纯纯的干货)
    iOS社会化分享(干货)
    静态库的打包及使用(干货)
    iOS地图集成示例:百度地图POI检索
    iOS开发之KVC全解
    网络干货
    输入一个字符串,按字典序打印出该字符串中字符的所有排列(剑指offer)
    序列化二叉树
    二叉树中和为某一值的路径
  • 原文地址:https://www.cnblogs.com/jianjiacangcang/p/14959320.html
Copyright © 2011-2022 走看看