[英]How to dump a YAML with an int with leading zeros?
I need to dump an integer with leading zeros, but not as a string.我需要转储一个带有前导零的整数,但不是作为字符串。 I can dump it like a string in this way:我可以用这种方式像字符串一样转储它:
import sys
from ruamel.yaml import YAML
data = {'identifier': '001'}
yaml = YAML()
yaml.dump(data, sys.stdout)
The result is:结果是:
identifier: '001'
I do not need to dump as a string, but as a number.我不需要转储为字符串,而是转储为数字。
I need a result like:我需要这样的结果:
identifier: 001
How can I do it?我该怎么做?
First thing to do if you need to check if a particular output can be generated is trying to round-trip the result:如果您需要检查是否可以生成特定输出,首先要做的是尝试往返结果:
import sys
import ruamel.yaml
yaml_str = """\
identifier: 001
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
data['another'] = double_o_one = data['identifier']
yaml.dump(data, sys.stdout)
which gives:这使:
identifier: 001
another: 001
So this proves this can be done programmatically, and if worst comes to worst and you cannot figure out how to make the double_o_one
from scratch, you can load it from a string.所以这证明了这可以通过编程来完成,如果最坏的情况出现在最坏的情况下并且您无法弄清楚如何从头开始制作double_o_one
,您可以从字符串中加载它。
If you investigate a bit more and have a look at the source of scalarint.py
:如果您进行更多调查并查看scalarint.py
的来源:
print(type(double_o_one))
print(double_o_one.__dict__)
print()
data['james'] = double_o_seven = ruamel.yaml.scalarint.ScalarInt(7, width=3)
yaml.dump(data, sys.stdout)
and that gives:这给出了:
<class 'ruamel.yaml.scalarint.ScalarInt'>
{'_width': 3, '_underscore': None}
identifier: 001
another: 001
james: 007
So if you start out with a string x = '001'
, you do x = ScalarInt(int(x), len(x))
因此,如果您从字符串x = '001'
开始,则执行x = ScalarInt(int(x), len(x))
>>> data = {'identifier': 0o001}
This will convert to an integer.这将转换为整数。 But , not in the format you specified.但是,不是您指定的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.