Python YAML: Controlling output format

Question:

My file reads user input (like userid, password..). And sets the data to x.yml file.

The content of x.yml file is

{user: id}

But instead I want the content to be as

user: id

How can I achieve this?

Asked By: user1643521

||

Answers:

As mentioned in the comments, the python YAML library is the right tool for the job. To get the output you want, you need to pass the keyword argument default_flow_style=False to yaml.dump:

>>> x = {"user" : 123}
>>> with open("output_file.yml", "w") as output_stream:
...     yaml.dump(x, output_stream, default_flow_style=False)

The file “output_file.yml” will contain:

user: 123

Further information on how to customise yaml.dump are available at http://pyyaml.org/wiki/PyYAMLDocumentation.

Answered By: Pascal Bugnion
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.