【问题标题】:Loading a YAML-file throws an error in Python加载 YAML 文件会在 Python 中引发错误
【发布时间】:2023-02-02 22:18:46
【问题描述】:

我正在阅读一些像这样的 YAML 文件:

data = yaml.safe_load(pathtoyamlfile)

这样做时出现以下错误:

yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:value'

在检查错误消息中也给出的 YAML 文件行时,我发现始终存在这个键值对:simple: =

由于 YAML 文件是自动生成的,我不确定是否可以自行更改文件。有没有办法读取 YAML 文件的数据?

【问题讨论】:

    标签: python python-3.x yaml


    【解决方案1】:

    看起来你打了this bug。 cmets 中建议了一个解决方法。

    鉴于example.yaml中的内容:

    example: =
    

    如您在问题中所述,此代码失败:

    import yaml
    
    with open('example.yaml') as fd:
      data = yaml.safe_load(fd)
    print(data)
    

    但这有效:

    import yaml
    
    yaml.SafeLoader.yaml_implicit_resolvers.pop('=')
    with open('example.yaml') as fd:
      data = yaml.safe_load(fd)
    print(data)
    

    并输出:

    {'example': '='}
    

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多