Python:从文件解析YAML数据

时间:2017-11-19 05:32:04

标签: python yaml

我的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

1 个答案:

答案 0 :(得分:2)

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']