从YAML文件中存储块,并使用Python将其附加到现有的YAML文件中

时间:2015-08-31 16:45:44

标签: python yaml pyyaml

我有大部分代码用于读取每个文件并转储到新文件。 我的下一步是存储car1(来自mom,file2)并将其添加到dad块下作为car2,file1)。

long Convert(float f);

template <typename First, typename... T>
int MyFun(const First& f, const T&... t) {
  return ComputeSomething(f, t...);
}

// This is what I would like:
int MyFun(const float& f, const float& t...) {
  return ComputeSomething(Convert(f), Convert(t)...);
}

新文件看起来像这样......包含car1和car2 for dad。

------
File 1
------
dad:
  car1:
    model: [toyota-venza]
    awd: true
    option:
      nav:
        backup_camera: true
        version: 1.35 
    mileage: 54,025
    year: 2000
age:
  ...

------
File 2
------
mom:
  car1:
    model: [toyota-camry]
    awd: false
    option:
      nav:
        backup_camera: false
        version: []
    mileage: 20,241
    year: 2013
age:
  ...

1 个答案:

答案 0 :(得分:0)

假设您使用键'car1'找到汽车信息,您可以使用该键搜索顶层映射中的值:

import ruamel.yaml as yaml
from ruamel.yaml.comments import CommentedMap
import glob

dad = CommentedMap()
dad['dad'] = d = CommentedMap()

for idx, file_name in enumerate(sorted(glob.glob('car*.yaml'))):
    data = yaml.load(open(file_name), Loader=yaml.RoundTripLoader)
    for k in data:
        if 'car1' in data[k]:
            new_key = 'car{0}'.format(idx+1)
            d[new_key] = data[k]['car1']
            d.yaml_add_eol_comment('# from {0} in {1}'.format(k, file_name),
                                   key=new_key, column=30)

print(yaml.dump(dad, Dumper=yaml.RoundTripDumper))

给你:

dad:
  car1:                       # from dad in car1.yaml
    model: [toyota-venza]
    awd: true
    option:
      nav:
        backup_camera: true
        version: 1.35
    mileage: 54,025
    year: 2000
  car2:                       # from mom in car2.yaml
    model: [toyota-camry]
    awd: false
    option:
      nav:
        backup_camera: false
        version: []
    mileage: 20,241
    year: 2013

假设文件car1.yamlcar2.yaml中的数据。我在这里使用ruamel.yaml¹来使用附加注释的有序地图。

您可以使用PyYAML执行此操作,但是您将失去保证的顺序和评论:

import yaml
import glob

dad = dict()
dad['dad'] = d = dict()

for idx, file_name in enumerate(sorted(glob.glob('car*.yaml'))):
    data = yaml.load(open(file_name), Loader=yaml.SafeLoader)
    for k in data:
        if 'car1' in data[k]:
            new_key = 'car{0}'.format(idx+1)
            d[new_key] = data[k]['car1']

print(yaml.dump(dad, Dumper=yaml.SafeDumper))

¹这是使用ruamel.yaml完成的,我是作者。