Python YAML:控制输出格式 [英] Python YAML: Controlling output format

查看:64
本文介绍了Python YAML:控制输出格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件读取用户输入(如用户ID,密码..).并将数据设置为x.yml文件.

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

x.yml文件的内容为

The content of x.yml file is

{user: id}

但是我希望内容保持原状

But instead I want the content to be as

user: id

我该如何实现?

推荐答案

如评论中所述,python YAML库是完成此任务的正确工具.要获得所需的输出,您需要将关键字参数 default_flow_style = False 传递给 yaml.dump :

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)

文件"output_file.yml"将包含:

The file "output_file.yml" will contain:

user: 123

有关如何自定义 yaml.dump 的更多信息,请访问 http://pyyaml.org/wiki/PyYAMLDocumentation .

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

这篇关于Python YAML:控制输出格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆