How to Save Values into a Yaml File

How would I save data in a YAML file in Python?

To read/write YAML, you'll need the PyYAML library installed, so do that with pip install PyYAML.

Then you could write a dict wrapper like

import os
import yaml

class YAMLPersistedDict:
def __init__(self, *, filename):
self.data = {}
self.filename = filename
self.load()

def load(self):
if os.path.isfile(self.filename):
with open(self.filename, "r") as fp:
self.data = yaml.safe_load(fp)

def save(self):
with open(self.filename, "w") as fp:
yaml.dump(self.data, fp)

def __getattr__(self, key):
# Pass through to dict
return getattr(self.data, key)

def __setitem__(self, key, value):
self.data[key] = value

def __getitem__(self, key):
return self.data[key]

def __repr__(self):
return f'<{self.filename!r}: {repr(self.data)}>'


d = YAMLPersistedDict(filename="./config.yaml")
d["servers"] = ["foo", "bar"]
d.save()

d = YAMLPersistedDict(filename="./config.yaml")
print(d)

Do note you'd need to call d.save() after every modification, and concurrent saves (especially since you're talking async Discord stuff) could break things.

Save values to file(e.g yml) in java


I'm missing sth like that Yaml-thing

SnakeYAML should have you covered. Without knowing anything about your use-case, it makes no sense to discuss its usage here since its documentation already does cover the general topics.

The only thing I found was a kind of a config file, where everytime the whole file is overwritten, when I try to add values.

Saving as YAML will always overwrite the complete file as well. Serialization does not really work with append-only. (Serialization is the term to search for when you want functionality like this, by the way.)

If you mean that previous values were deleted, that probably was because you didn't load the file's content before or some other coding error, but since you don't show your code, we can only speculate.

Can you show me a proper way of saving values to a file?

People will have quite different opinions on what would be a proper way and therefore it is not a good question to ask here. It also heavily depends on your use-case.

would be nice without libraries

So you're basically saying „previously I used a library which had a nice feature but I want to have that feature without using a library“. This stance won't get you far in today's increasingly modular software world.

For example, JAXB which offers (de)serialization from/to XML was previously part of Java SE, but has been removed as of Java SE 11 and is a separate library now.

How do you save values into a YAML file?

Using ruby-1.9.3 (Approach may not work in older versions).

I'm assuming the file looks like this (adjust code accordingly):

---
content:
session: 0

and is called /tmp/test.yml

Then the code is just:

require 'yaml' # Built in, no gem required
d = YAML::load_file('/tmp/test.yml') #Load
d['content']['session'] = 2 #Modify
File.open('/tmp/test.yml', 'w') {|f| f.write d.to_yaml } #Store

How can I write data in YAML format in a file?


import yaml

data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)

with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

How to save [x, y] in yaml file

No you can not, not in the way that you describe. You can easily test that by pasting your required output in an online YAML parser (e.g. this one) or, if you have Python installed, by installing a virtualenv and do¹:

pip install ruamel.yaml.cmd
yaml round-trip input.yaml

Your required output has, at the top-level, a mapping with key world, for which the value starts out with being a mapping (with key radius and value 20) then switches to a flow style sequence: [-30, -70]. That is incorrect, you cannot mix mapping key-value pairs with sequences.

There are several ways to correct this. You can do:

world:
radius: 20
[-30, -70]:

which is perfectly fine YAML, the pair -30, -70 being a key for a value null which doesn't need to be made explicit. Please note that some YAML parsers do not support this form, the one I linked to does.

The, IMO, most logical one-line solution:

world:
radius: 20
[x, y]: [-30, -70]

which you can get by compiling and running:

#include <iostream>
#include "yaml-cpp/yaml.h"

int main()
{
YAML::Emitter out;
out << YAML::BeginMap;
out << YAML::Key << "world";
out << YAML::Value << YAML::BeginMap;
out << YAML::Key << "radius";
out << YAML::Value << 20;
out << YAML::Key << YAML::Flow << YAML::BeginSeq << "x" << "y" << YAML::EndSeq;
out << YAML::Key << YAML::Flow << YAML::BeginSeq << "-30" << "-70" << YAML::EndSeq;

std::cout << out.c_str() << "\n";
return 0;
}

Your first YAML example is invalid YAML as well: you should align the keys and not the colons in a mapping:

world:     

radius: 20
x: -70
y: -30

¹ Disclaimer: I am the author of the ruamel.yaml.cmd package. Using a local test can be important if your YAML file contains sensitive data.

Edit yaml file and save it with python

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)

How can I store my variables in yaml file?

If you want to use YAML in PHP, you need to install the extension with PECL:

pecl install yaml

If it fails with a libtool version mismatch error, you will need to download it first, compile and install it yourself, and enable it in the php.ini file.

Once that's done, you can easily parse your file by getting its content and running the parse function, like so:

$vars = yaml_parse( file_get_contents( './vars.yml' ) );

How to save yaml key-values with the root key in Python?

If you want to output a single key-value pair, you need to give a dict with one entry:

yaml.dump(dict(images=data.get("images")), outfile, default_flow_style=False)


Related Topics



Leave a reply



Submit