user1643521
user1643521

Reputation: 2351

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?

Upvotes: 27

Views: 49660

Answers (1)

Pascal Bugnion
Pascal Bugnion

Reputation: 4928

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.

Upvotes: 52

Related Questions