简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM