简体   繁体   English

编辑yaml文件并用python保存

[英]Edit yaml file and save it with python

I have a yaml file that looks like this:我有一个 yaml 文件,如下所示:

grids:
  phxgrid:
    class: spexxy.grid.FilesGrid
    filename: /home/geoffrey/Bureau/husser_interpolator/grid.csv

interpolators:
  phx:
    class: spexxy.interpolator.SplineInterpolator
    grid: phxgrid
    derivs: phxgrid

components:
  star:
    class: spexxy.component.GridComponent
    interpolator: phx
    init:
    - class:    
      values:
        logg: 4.0
        Alpha: 0.
        v: 0
        sig: 0


main:
  class: spexxy.main.ParamsFit
  components: [star]
  fixparams:
    star: [sig, Alpha, logg]

From a CSV file, I have to read a parameter in a column, which I already know how to do, and insert it in the yaml file to the line logg: 4.0 , by example switching 4.0 to 3.2, and save a yaml file for each value.从 CSV 文件中,我必须读取一列中的参数,我已经知道该怎么做,然后将其插入到 yaml 文件中的行logg: 4.0 ,例如将 4.0 切换到 3.2,并保存一个 yaml 文件以供每个值。

Would you know how to do this?你知道怎么做吗? Thanks谢谢

EDIT:编辑:

So, for now, I have this:所以,现在,我有这个:

import csv
import yaml
from csv import reader

with open('params.csv', 'r') as f:
        data = list(reader(f))
        logg_list = [i[6] for i in data[1::]]

with open('config.yaml', 'rw') as ymlfile:
        doc = yaml.load(ymlfile)

for logg in logg_list:
        doc['logg'] = logg[i]
        yaml.dump(doc,ymlfile)

But it does not change anything, and I'm not sure about the saving part as I'm supposed to obtain many yaml files with different values of logg, and I'd like to name the valid files in consequence但它不会改变任何东西,我不确定保存部分,因为我应该获得许多具有不同 logg 值的 yaml 文件,因此我想命名有效文件

There's no need to read the entire CSV file into memory.无需将整个 CSV 文件读入内存。 Read the YAML configuration in first, then write new YAML files as you iterate through the CSV file.首先读取 YAML 配置,然后在迭代 CSV 文件时编写新的 YAML 文件。

from csv import reader
import yaml


with open('config.yaml') as f:
    doc = yaml.load(f)

values = doc['components']['star']['init'][0]['values']
with open('params.csv') as f:
    for i, record in enumerate(reader(f)):
        values['logg'] = record[6]
        with open(f'config-{i}.yaml', 'w') as out:
            yaml.dump(doc, out)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM