Tech and travel

Using YAML in Python

2008-02-18

YAML, which stands for ‘YAML Ain’t Markup Language’, is basically XML without < and > . This makes it very readable. Additionally, in dynamic languages such as Python, the data in the file will be loaded as a Python data structure. Here’s an example file :

http://www.infoworld.com/rss/news.xml: (1970, 1, 1, 1, 0, 0, 3, 1, 0)
http://weblog.infoworld.com/udell/rss.xml: (1970, 1, 1, 1, 0, 0, 3, 1, 0)
http://weblog.infoworld.com/techwatch/rss.xml: (1970, 1, 1, 1, 0, 0, 3, 1, 0)

This will be loaded into a dictionary, with each URL as a key. Other data types can be stored in the file as well, such as lists.

import yaml

d=yaml.load(open('new_links.yaml').read())
for key in d.keys():
    item=d[key]
    print item
print
print "Dump :"
d['http://www.infoworld.com/rss/news.xml']='(2008, 2, 18, 1, 10, 9, 3, 1, 0)'
print yaml.dump(d, default_flow_style=False)

This program loads the new_links.yaml file using the yaml.load function. It then loops over all they keys in the dictionary and prints out the value associated with that key.

Then the value for the key ‘http://www.infoworld.com/rss/news.xml' is changed to ‘(2008, 2, 18, 1, 10, 9, 3, 1, 0)’. Lastly the dump function is used to print out the dictionary as YAML. This can be used to save to a file as well.

This is the output :

(1970, 1, 1, 1, 0, 0, 3, 1, 0)
(1970, 1, 1, 1, 0, 0, 3, 1, 0)
(1970, 1, 1, 1, 0, 0, 3, 1, 0)

Dump :
http://weblog.infoworld.com/techwatch/rss.xml: (1970, 1, 1, 1, 0, 0, 3, 1, 0)
http://weblog.infoworld.com/udell/rss.xml: (1970, 1, 1, 1, 0, 0, 3, 1, 0)
http://www.infoworld.com/rss/news.xml: (2008, 2, 18, 1, 10, 9, 3, 1, 0)

A YAML library for Python is PyYAML. This is a pure Python library, so it doesn’t need a C library.

Copyright (c) 2024 Michel Hollands