如何检查 yaml 文件中是否存在密钥 Python

How do I check if a key exists in a yaml file Python

我正在尝试检查 yaml 文件中是否存在用户名

我的文件格式为:

random_uuid:
    username: ""
random_uuid:
    username: ""
random_uuid:
    username: ""

谷歌搜索后我仍然不确定该怎么做,因为它必须查看所有 uuid

如果这是您的 YAML 文件的结构,只需迭代所有值,直到找到您要查找的内容。假设文件在 test.yaml:

#!/usr/bin/env python
import yaml

FILE_PATH = "test.yaml"
LOOKING_FOR_THIS_USER = "Shay"

with open(FILE_PATH, "r") as stream:
    try:
        loaded_yaml = yaml.safe_load(stream)
        for k, v in loaded_yaml.items():
            print(f"{k=}: {v=}")
            if v['username'] == LOOKING_FOR_THIS_USER:
                print(f"Found it! {k} is the user we looked for.")
    except yaml.YAMLError as exc:
        print(exc) 

您可以使用 yaml (pyyaml) 模块,并将加载视为 python 字典。

import yaml

document = """
  123:
    a: ''
    b: ''
    c: ''
  456:
    a: ''
    b: ''
    c: ''
"""
yaml.dump(yaml.safe_load(document))
doc = yaml.safe_load(document)

for key in (123, 456, 789):
    try:
        print(f'{key} - {doc[key]} found')
    except KeyError:
        print(f'{key} - not found')