---
title: "python 读写yaml "
author: "sg552"
date: "2012-08-06T10:39:30Z"
tags: []
categories: ["编程语言"]
slug: "python-yaml"
draft: false
lastmod: "2012-08-06T12:57:43Z"
id: 1622088
url: "https://sg552.iteye.com/blog/1622088"
---

<http://mikkel.elmholdt.dk/?p=4>

1. install pyyaml:  (<http://pyyaml.org/wiki/PyYAMLDocumentation>)
1.1 wget http://pyyaml.org/download/pyyaml/PyYAML-3.01.tar.gz
1.2 tar zxvf PyYAML-3.01.tar.gz
1.3 cd PyYAML-3.01 && python setup.py install


```yaml
# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

```



```python

import yaml
f = open('tree.yaml')
dataMap = yaml.load(f)
f.close()

# dataMap: 
{'treeroot': {'branch1': {'branch1-1': {'name': 'Node 1-1'},
    'name': 'Node 1'},
    'branch2': {'branch2-1': {'name': 'Node 2-1'},
    'name': 'Node 2'}}}


```



```python
f = open('newtree.yaml', "w")
yaml.dump(dataMap, f)
f.close()

```