簡體   English   中英

Python:從文件中解析YAML數據

[英]Python: YAML data parsing from a file

我有以下YAML數據

- gms:
  - localhost1:
      address: 192.168.56.101
      username: root
      password: xxxxxx
      command: "uptime"
      hostname: mydev_machine

我正在嘗試使用以下邏輯在python中提取addresspasswordcommandhostname

import yaml

with open("host_data.yaml",'r') as stream :
  data_loaded = yaml.load(stream)

for element in data_loaded:
  address=element['gms']['localhost1']['address']
  username=element['gms']['localhost1']['username']
  password=element['gms']['localhost1']['password']
  hostname=element['gms']['localhost1']['hostname']

如果我看一下print(data_loaded)輸出

[{'gms': [{'localhost1': {'address': '192.168.56.101', 'username': 'root', 'password': 'xxxxxx', 'command': 'uptime', 'hostname': 'mydev_machine'}}]}]

但我得到錯誤

Traceback (most recent call last):
  File "Python_Programs/log_finder.py", line 12, in <module>
    address=element['gms']['localhost1']['address']
TypeError: list indices must be integers or slices, not str

element.get('gms')element['gms']產生一個列表。 您需要迭代列表。

for element in data_loaded:
    for item in element.get('gms'):
        print(item.get('localhost1').get('address'))

您還可以像這樣訪問list的元素:

element['gms'][0]['localhost1']['address']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM