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?
In this case, yaml. dump will write the produced YAML document into the file. Otherwise, yaml. dump returns the produced document.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With