Handling yaml with python

Overview

How to write in block style when handling yaml in python Use PyYAML

Read / write

Suppose you have a yaml file like this

test1: test
test2: test

It can be read in dictionary type as shown below.

>>> import yaml
>>> f = open("test.yml", "r+")
>>> data = yaml.load(f)
>>> data
{'test1': 'test', 'test2': 'test'}

When writing, write with dump () as follows.

>>> data
{'test1': 'test', 'test2': 'test'}
>>> f.write(yaml.dump(data))
>>> f.close()

Looking at the written test.yml, it looks like the following, which is not as expected. Very hard to see.

test1: test
test2: test
{test1: test, test2: test}

Write in block style

To write in block style instead of flow style, set default_flow_style = False atdump ().

>>> f.write(yaml.dump(data, default_flow_style=False))
test1: test
test2: test
test1: test
test2: test

It's as expected.

Write using OrderedDict

When converting an instance object to yaml with dump (), there is a problem that the tag of the instance object is output. For example, Ordered Dict that is How to change the behavior when loading / dumping yaml with PyYAML and its details .

reference

http://gihyo.jp/dev/serial/01/yaml_library/0003 http://blog.panicblanket.com/archives/1076

Recommended Posts

Handling yaml with python
Think yaml with python
Auto-complete YAML content with Python
Handling regular expressions with PHP / Python
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
Python Error Handling
Python exception handling
python starts with ()
with syntax (Python)
Bingo with python
Python timezone handling
Zundokokiyoshi with python
Excel with Python
Python exception handling
Microcomputer with Python
Cast with python
Serial communication with Python
Zip, unzip with python
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Sequential search with Python
"Object-oriented" learning with python
Run Python with VBA
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learning Python with ChemTHEATER 05-1
Learn Python with ChemTHEATER
Run prepDE.py with python3
1.1 Getting Started with Python
Collecting tweets with Python
Binarization with OpenCV / Python
3. 3. AI programming with Python
Handling json in python
Kernel Method with Python
Non-blocking with Python + uWSGI
Scraping with Python + PhantomJS
Posting tweets with python
Drive WebDriver with python
Use mecab with Python3
[Python] Redirect with CGIHTTPServer
Voice analysis with python
Operate Kinesis with Python
Getting Started with Python
Use DynamoDB with Python
Zundko getter with python
Handle Excel with python
Ohm's Law with Python