问题描述
我有以下 YAML 文件:
I have the following YAML file:
---
my_vars:
my_env: "dev"
my_count: 3
当我用 PyYAML 读取它并再次转储时,我得到以下输出:
When I read it with PyYAML and dump it again, I get the following output:
---
my_vars:
my_env: dev
my_count: 3
有问题的代码:
with open(env_file) as f:
env_dict = yaml.load(f)
print(yaml.dump(env_dict, indent=4, default_flow_style=False, explicit_start=True))
我尝试使用 default_style
参数:
with open(env_file) as f:
env_dict = yaml.load(f)
print(yaml.dump(env_dict, indent=4, default_flow_style=False, explicit_start=True, default_style='"'))
但现在我明白了:
---
"my_vars":
"my_env": "dev"
"my_count": !!int "3"
我需要做什么来保持原始格式,对 YAML 文件中的变量名称做任何假设?
What do I need to do to keep the original formatting, without making any assumptions about the variable names in the YAML file?
推荐答案
我建议您更新为使用 YAML 1.2(2009 年发布)和向后兼容的 ruamel.yaml
包,而不是使用实现大部分 YAML 1.1 (2005) 的 PyYAML.(免责声明:我是该软件包的作者).
I suggest you update to using YAML 1.2 (released in 2009) with the backwards compatible ruamel.yaml
package instead of using PyYAML which implements most of YAML 1.1 (2005). (Disclaimer: I am the author of that package).
然后您只需在加载以往返 YAML 文件时指定 preserve_quotes=True
:
Then you just specify preserve_quotes=True
when loading for round-tripping the YAML file:
import sys
import ruamel.yaml
yaml_str = """\
---
my_vars:
my_env: "dev" # keep "dev" quoted
my_count: 3
"""
data = ruamel.yaml.round_trip_load(yaml_str, preserve_quotes=True)
ruamel.yaml.round_trip_dump(data, sys.stdout, explicit_start=True)
输出(包括保留的评论):
which outputs (including the preserved comment):
---
my_vars:
my_env: "dev" # keep "dev" quoted
my_count: 3
加载字符串后,标量将成为字符串的子类,以便能够容纳引用信息,但对于所有其他目的,它将像普通字符串一样工作.如果你想替换这样的字符串(dev
到 fgw
)您必须将字符串转换为该子类(ruamel.yaml.scalarstring
中的 DoubleQuotedScalarString
).
After loading the string scalars will be a subclass of string, to be able to accommodate the quoting info, but will work like a normal string for all other purposes. If you want to replace such a string though (dev
to fgw
)you have to cast the string to this subclass ( DoubleQuotedScalarString
from ruamel.yaml.scalarstring
).
当往返 ruamel.yaml
默认保留键的顺序(通过插入).
When round-tripping ruamel.yaml
by default preserves the order (by insertion) of the keys.
这篇关于pyyaml 并仅对字符串使用引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!