如何以人性化的方式保存Python Yaml库?
下面是我得到的Python代码:如何以人性化的方式保存Python Yaml库?,python,file,configuration,yaml,human-readable,Python,File,Configuration,Yaml,Human Readable,下面是我得到的Python代码: d = {'ToGoFirst': 'aaa', 'Second': 'bbb', 'Pagargaph': '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''', 'Integer': 25} with open('d.yaml', 'w') as
d = {'ToGoFirst': 'aaa', 'Second': 'bbb', 'Pagargaph':
'''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.''',
'Integer': 25}
with open('d.yaml', 'w') as f:
yaml.safe_dump(d, f, default_flow_style=False)
我一直得到的是:
Integer: 25
Pagargaph: "Lorem ipsum dolor sit amet, \nconsectetur adipiscing elit, \nsed do eiusmod\
\ tempor incididunt \nut labore et dolore magna aliqua."
Second: bbb
ToGoFirst: aaa
如何更改它以生成:
ToGoFirst: aaa
Second: bbb
Pagargaph:
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
Integer: 25
换句话说,我想:
这是为了能够加载YAML文件,添加更多参数,并且仍然能够以人性化的格式保存它。您的输出在
Pagargaph
的值中没有换行符,因此您需要有一个(破折号修剪最后的换行符,加载这样的标量时通常会得到):
您应该使用(免责声明:我是该软件包的作者),它是专门为支持这种往返而开发的。要获得您想要的,请执行以下操作:
import sys
import ruamel.yaml
from ruamel.yaml.scalarstring import PreservedScalarString as L
yaml_str = """\
ToGoFirst: aaa
Second: 'bbb' # insert after this one
Integer: 25
"""
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
d = yaml.load(yaml_str)
# yaml.indent(mapping=4, sequence=4, offset=2)
try:
before_integer = [k for k in d].index('Integer')
except ValueError:
before_integer = len(d)
d.insert(before_integer, 'Pagargaph', L('''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''))
d.insert(before_integer, 'Something', 'extra', comment='with a comment')
yaml.dump(d, sys.stdout)
导致:
ToGoFirst: aaa
Second: 'bbb' # insert after this one
Something: extra # with a comment
Pagargaph: |-
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
Integer: 25
请注意:
- 在ruamel.yaml(2.7,3.4+)支持的任何Python版本中都会保留该顺序
- 该评论将被保留
- 仅当您指定
yaml.preserve\u quotes=True
- 因为我们在位置2插入了两次,所以后者将前者碰撞到位置3
:
后面跟空格,#
前面跟空格)
为了帮助防止用户犯编辑错误,您可以尝试在YAML文档的开头添加以下注释:
# please read the first few "rules" of How_to_edit at the bottom of this file
最后:
How_to_edit: |
Editing a YAML document is easy, but there are some rules to keep you from
accidently invoking its hidden powers. Of the following you need at least
read and apply the ones up to the divider separating the important from less
important rules. The less important ones are interesting, but you probably
won't need to know them.
1) Entries in this file consist of a scalar key (before the ':') and a scalar
value (normally after the ':', but read rule 3).
2) Scalars do NOT need quotes (single: ', or double: ") around them, unless
you have a special character or characters combinations at the beginning
('%', '*', '&', '{', '[', '- ') or in the middle (': ', ' #) of the scalar.
If you add quotes use a single quote before and after the scalar . If
these are superfluous the program can remove them. So when in doubt just
add them.
3) A key followed by ': |' introduces a multiline scalar. These instructions
are in a multiline scalar. Such a scalar starts on the next line after ': |'.
The lines need to be indented, until the end of the scalar and these
indentation spaces are not part of the scalar.
The newlines in a multiline sclar are hard (i.e. preserved, and not
substituted with spaces).
If you see `: |-` that means the scalar is loaded with the trailing newline
stripped.
4) Anything after a space followed by a hash (' #') is a comment, when not
within quotes or in a multiline string.
--- end of the important rules ---
5) Within single quoted scalars you can have a single quote by doubling it:
rule 4: 'you probably don''t ever need that'
This is called escaping the single quote. You can double quote scalars, but
the rules for escaping are much more difficult, so don't try that at home.
6) The scalars consisting solely of "True" and "False" (also all-caps and
all-lowercase) are loaded as booleans when unquoted, and as strings when
quoted.
7) Scalars consisting solely of number characters (0-9) are loaded as numbers.
If there is a non-number they are usually loaded as strings, but scalars
starting with '0x' and '0o' and for the rest have only number characters,
are special and need quotes if not intended as (hexadecimal resp. octal)
numbers.
如果包含上述内容,则可能不希望在往返时保留引号。您的预期/期望输出示例是错误的。在纯标量中,你不能产生你所拥有的。有多行尾随空格,pyyaml决定对此使用双引号。另一种选择是文字块标量。参数的顺序可能会保留在下一个版本的pyyaml中(当使用python 3.6/3.7运行时)。目前,它总是对密钥进行排序,但有一种方法允许禁用它。或者试试ruamel.yamlThank。我可以去掉“|-”但仍然满足YAML规范吗?是的,可以,但标量中不会有任何换行符,您看到的换行符,行首后面的所有空格都将替换为空格。这与你的“Lorem ipsum…”不同,它有三个嵌入的换行符(当然,这可能对你的应用程序没有影响,但我不知道)。我的意思是,我能以某种方式去掉“|-”并且仍然有换行符吗?换句话说,我怎样才能使输出完全非技术友好?你不能。你的技术人员必须学习一些东西,比如何时引用,何时不引用,他们需要缩进,等等。如果您的数据结构只包含根级别的映射(没有嵌套的映射和序列),那么您应该能够通过一些预处理来解析它,但在这种情况下,您也可以不使用YAML进行解析。我更新了我的答案,并建议添加基本的编辑说明。但它们并不完整。
How_to_edit: |
Editing a YAML document is easy, but there are some rules to keep you from
accidently invoking its hidden powers. Of the following you need at least
read and apply the ones up to the divider separating the important from less
important rules. The less important ones are interesting, but you probably
won't need to know them.
1) Entries in this file consist of a scalar key (before the ':') and a scalar
value (normally after the ':', but read rule 3).
2) Scalars do NOT need quotes (single: ', or double: ") around them, unless
you have a special character or characters combinations at the beginning
('%', '*', '&', '{', '[', '- ') or in the middle (': ', ' #) of the scalar.
If you add quotes use a single quote before and after the scalar . If
these are superfluous the program can remove them. So when in doubt just
add them.
3) A key followed by ': |' introduces a multiline scalar. These instructions
are in a multiline scalar. Such a scalar starts on the next line after ': |'.
The lines need to be indented, until the end of the scalar and these
indentation spaces are not part of the scalar.
The newlines in a multiline sclar are hard (i.e. preserved, and not
substituted with spaces).
If you see `: |-` that means the scalar is loaded with the trailing newline
stripped.
4) Anything after a space followed by a hash (' #') is a comment, when not
within quotes or in a multiline string.
--- end of the important rules ---
5) Within single quoted scalars you can have a single quote by doubling it:
rule 4: 'you probably don''t ever need that'
This is called escaping the single quote. You can double quote scalars, but
the rules for escaping are much more difficult, so don't try that at home.
6) The scalars consisting solely of "True" and "False" (also all-caps and
all-lowercase) are loaded as booleans when unquoted, and as strings when
quoted.
7) Scalars consisting solely of number characters (0-9) are loaded as numbers.
If there is a non-number they are usually loaded as strings, but scalars
starting with '0x' and '0o' and for the rest have only number characters,
are special and need quotes if not intended as (hexadecimal resp. octal)
numbers.