简体   繁体   中英

Edit yaml file and save it with python

I have a yaml file that looks like this:

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.

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

There's no need to read the entire CSV file into memory. Read the YAML configuration in first, then write new YAML files as you iterate through the CSV file.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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