Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python YAML: Controlling output format

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?

like image 858
user1643521 Avatar asked Sep 03 '12 11:09

user1643521


People also ask

What does YAML dump return?

In this case, yaml. dump will write the produced YAML document into the file. Otherwise, yaml. dump returns the produced document.

Is PyYAML same as YAML?

YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages.

What is YAML Safe_load?

Loading a YAML Document Safely Using safe_load() safe_load(stream) Parses the given and returns a Python object constructed from the first document in the stream. safe_load recognizes only standard YAML tags and cannot construct an arbitrary Python object.

Does YAML support tuple?

Support for Python builtin types and mappings of other types onto YAML syntax. Objects of commonly used Python builtin types may be tersely expressed in YamlConfig. Supported types are str, unicode, int, long, float, decimal. Decimal, bool, complex, dict, list and tuple.


1 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.

like image 172
Pascal Bugnion Avatar answered Sep 22 '22 19:09

Pascal Bugnion