I have a YAML file that looks like this:
# Sense 1 - name : sense1 type : float value : 31 # sense 2 - name : sense2 type : uint32_t value : 1488 # Sense 3 - name : sense3 type : int32_t value : 0 - name : sense4 type : int32_t value : 0 - name : sense5 type : int32_t value : 0 - name : sense6 type : int32_t value : 0
I want to use Python to open this file, change some of the values (see above) and close the file. How can I do that ?
For instance I want to set sense2[value]=1234, keeping the YAML output the same.
You can open a YAML file in any text editor, such as Microsoft Notepad (Windows) or Apple TextEdit (Mac). However, if you intend to edit a YAML file, you should open it using a source code editor, such as NotePad++ (Windows) or GitHub Atom (cross-platform).
We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.
Write YAML File In PythonOpen config.py and add the following lines of code just below the read_yaml method and above the main block of the file. In the write_yaml method, we open a file called toyaml. yml in write mode and use the YAML packages' dump method to write the YAML document to the file.
YAML natively supports three basic data types: scalars (such as strings, integers, and floats), lists, and associative arrays. The official recommended filename extension for YAML files has been . yaml . There are two modules in Python for YAML: PyYAML and ruamel.
If you care about preserving the order of your mapping keys, the comment and the white space between the elements of the root-level sequence, e.g. because this file is under revision control, then you should use ruamel.yaml
(disclaimer: I am the author of that package).
Assuming your YAML document is in the file input.yaml
:
import sys import ruamel.yaml yaml = ruamel.yaml.YAML() # yaml.preserve_quotes = True with open('input.yaml') as fp: data = yaml.load(fp) for elem in data: if elem['name'] == 'sense2': elem['value'] = 1234 break # no need to iterate further yaml.dump(data, sys.stdout)
gives:
# Sense 1 - name: sense1 type: float value: 31 # sense 2 - name: sense2 type: uint32_t value: 1234 # Sense 3 - name: sense3 type: int32_t value: 0 - name: sense4 type: int32_t value: 0 - name: sense5 type: int32_t value: 0 - name: sense6 type: int32_t value: 0
This can safely be used on untrusted YAML. The (default) RoundtripLoader
is a subclass of the SafeLoader
even though it can handle and preserve tags (which it doesn't interpret in the dangerous way PyYAML does when enabling loading of unregistered tags).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With