Use YMAL Configuration File

Introduction

YAML is a human-readable data serialization language. It is commonly used for configuration files and in applications where data is being stored or transmitted. (Wikipedia)

YAML stands for "YAML Ain't Markup Language" (which emphasizes that YAML is for data, not documents); Also referred to as "Yet Another Markup Language".

It has a file type of .yml or .yaml.

Note: A markup language is a text-encoding system which specifies the structure and formatting of a document and potentially the relationship between its parts. Markup can control the display of a document or enrich its content to facilitate automated processing.

Project #1

There are many of the projects that have hard coded configurations as part of the code. Pick one or more and convert them to use a YAML configuration file. For example:

Install YAML (pyyaml module)

pip install pyyaml

python -m pip install pyyaml

YAML Example 1

YAML configuration file (using an editor)

# friend/work phonebook phonebook: title: 'My Phone Book' friends: dave: 234-5431 barbara: 555-667-4510 work: - 666-6666 - 777-7777

read a YAML configuration file created with an editor

import yaml from pprint import pprint with open('yaml_003.yml','r') as f: config = yaml.safe_load(f) ##print(config) ##for k,v in config['phonebook']['friends'].items(): ## print(k,' ',v) pprint(config, sort_dicts=False)

YAML Example 2

write YAML configuration file (using Python)

import yaml filename = 'yaml_001.yml' config: dict[str,any] = { 'admin':'Tom', 'title':'My Guessing Game Config File', 'guesses':5, 'limits':{'max':0,'min':100} } yaml_output = yaml.dump(config, sort_keys=False) ##print(yaml_output) with open(filename, 'w') as f: f.write(yaml_output) print(f'YAML file {filename} created')

read YAML configuration file (using Python)

import yaml with open('yaml_001.yml','r') as f: config = yaml.safe_load(f) ##print(config) print(f"admin = {config['admin']}") print(f"title = {config['title']}") print(f"limit min = {config['limits']['min']}") print(f"limit max = {config['limits']['max']}") print(f"guesses = {config['guesses']}")

Links

The Official YAML Web Site

Python YAML: How to Load, Read, and Write YAML

How to Work with YAML in Python

YAML cheatsheet

All you need to know about YAML Files!

Working with YAML Files in Python (YouTube)

How to Load, Read, Write YAML

Starting With YAML and PyYAML in Python (YouTube)