• 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))
    
    
  • 相关阅读:
    C# List<T>用法(转)
    任务列表 (Visual Studio)
    TSQL行转列、列转行
    HRESULT:0x80070057 (E_INVALIDARG)的异常的解决方案(转)
    JS正则表达式详解(转)
    Windows远程登录命令
    JavaScript中的try...catch和异常处理(转)
    javascript如何触发button 的click事件
    在ASP.NET中利JavaScript实现控件的聚焦(转)
    输入一个字符串,将其逆序后输出。(使用C++,不建议用伪码)
  • 原文地址:https://www.cnblogs.com/jianjiacangcang/p/14959320.html
Copyright © 2020-2023  润新知