如何用Python结合PyYAML遍历YAML并筛选source=gke的路径值
使用PyYAML筛选YAML中source为gke的数据并循环处理path
步骤1:安装PyYAML模块
若未安装PyYAML,先执行以下命令完成安装:
pip install pyyaml
步骤2:Python代码实现
场景1:YAML内容保存在文件中
假设你的YAML数据存储在data.yaml文件里,代码示例如下:
import yaml # 读取并加载YAML文件 with open('data.yaml', 'r') as file: yaml_data = yaml.safe_load(file) # 筛选出source为gke的数据项 gke_items = [item for item in yaml_data['data'] if item.get('source') == 'gke'] # 循环遍历筛选结果,将path赋值给变量并处理 for item in gke_items: path_variable = item['path'] # 此处可添加对path_variable的实际业务处理逻辑 print(f"当前path值:{path_variable}")
场景2:YAML内容以字符串形式存在代码中
如果YAML数据直接写在代码里,可使用以下方式处理:
import yaml yaml_str = """ data: - name: acme_aws1 source: aws path: acme/acme_aws1.zip - name: acme_gke1 source: gke path: acme/acme_gke1.zip - name: acme_oci source: oci path: acme/acme_oci1.zip - name: acme_aws2 source: aws path: acme/acme_aws2.zip - name: acme_gke2 source: gke path: acme/acme_gke2.zip - name: acme_oci2 source: oci path: acme/acme_oci2.zip """ # 加载字符串形式的YAML数据 yaml_data = yaml.safe_load(yaml_str) # 筛选并循环处理 gke_items = [item for item in yaml_data['data'] if item.get('source') == 'gke'] for item in gke_items: path_variable = item['path'] # 替换为你的实际处理逻辑 print(path_variable)
关键说明
- 优先使用
yaml.safe_load()而非yaml.load(),避免加载不可信YAML时的安全风险。 - 列表推导式可高效筛选符合条件的数据项,
item.get('source')能避免因部分数据缺失source字段导致的报错。 - 循环中每次将
path值赋值给path_variable后,可根据需求替换打印逻辑为具体业务操作。
内容的提问来源于stack exchange,提问作者hare krshn
相关产品推荐
相关产品推荐

