YAML
“YAML Ain’t Markup Language” (abbreviated YAML) is a human-readable data serialization standard that can be used in conjunction with all programming languages and is often used to write configuration files. YAML is designed to be useful and friendly to people working with data. Its features are derived from Perl, C, HTML, and other languages. YAML is a superset of JSON that comes with multiple built-in advantages such as including comments, self-referencing, and support for complex data types. Full documentation for YAML can be found on its official site.
YAML file
A YAML file is just a flat file value with key : value pairs. YAML supports strings, integers, floats, lists, and associative arrays.
datadir: 'data/'
db: 'data/rawtweets.sqlite'
filter: ['aerobic', 'anaerobic']
api_key: 'kn3tkFsvJaJi3'
token: '11062wsT2b7xFkVe4'
The configuration data can be read by the yaml.safe_load()
function from the yaml
library.
""" function that fetches the configuration
parameters from config.yaml
"""
import yaml
def get_config():
with open("config.yaml", 'r') as stream:
config = yaml.safe_load(stream)
return config
The PyYAML module transforms the values into a Python dictionary. In your python code, you can use this python dictionary just like an ordinary dictionary.
config = get_config()
db = (config['db'])
yaml.dump()
with yaml.dump()
we can write to configuration files.
users = [{'name': 'Fenna', 'occupation': 'teacher'},
{'name': 'Tijs', 'occupation': 'student-assistent'}]
with open('users.yaml', 'w') as f:
data = yaml.dump(users, f)
Last updated
Was this helpful?