我有一个特定的格式,我想将元组转储到YAML文件中。我尝试运行以下代码将元组转储到YAML文件中。在下面的代码中,我尝试使用append()将一对元组(x,y)添加到列表中。在此之后,我会将列表转储回YAML文件。我的问题是,当我转储回YAML文件时,是否可以保持文件的特定格式不变?
import ruamel.yaml
def addObstacles():
yaml = ruamel.yaml.YAML()
with open('input.yaml') as f:
doc = yaml.load(f)
x = 5
y = 6
doc['map']['obstacles'].append(list((x,y)))
with open('input.yaml', 'w') as f:
yaml.dump(doc, f)以下文件的输出如下:
map:
dimensions: [8, 8]
obstacles:
- !!python/tuple [4, 5]
- !!python/tuple [2, 0]
- !!python/tuple [1, 1]
- !!python/tuple [0, 5]
- !!python/tuple [2, 5]
- !!python/tuple [4, 4]
- !!python/tuple [7, 5]
- !!python/tuple [1, 4]
- !!python/tuple [6, 7]
- !!python/tuple [6, 3]
- !!python/tuple [1, 7]
- !!python/tuple [3, 6]
- - 5
- 6该文件的预期输出如下:
map:
dimensions: [8, 8]
obstacles:
- !!python/tuple [4, 5]
- !!python/tuple [2, 0]
- !!python/tuple [1, 1]
- !!python/tuple [0, 5]
- !!python/tuple [2, 5]
- !!python/tuple [4, 4]
- !!python/tuple [7, 5]
- !!python/tuple [1, 4]
- !!python/tuple [6, 7]
- !!python/tuple [6, 3]
- !!python/tuple [1, 7]
- !!python/tuple [3, 6]
- !!python/tuple [5, 6]发布于 2019-12-22 16:56:22
既然你追加了一个列表,你就会得到一个列表,但我假设你试过了,因为一个普通的元组不能工作,因为你实际上在ruamel.yaml中发现了一个bug。
只需两行代码并指定default_flow_style,就可以很容易地解决这个问题
import sys
import ruamel.yaml
if ruamel.yaml.version_info < (0, 16, 7):
ruamel.yaml.representer.RoundTripRepresenter.add_representer(tuple,
ruamel.yaml.representer.Representer.represent_tuple)
def addObstacles():
yaml = ruamel.yaml.YAML()
yaml.default_flow_style = None # default is False, which would get you a block sequence
with open('input.yaml') as f:
doc = yaml.load(f)
doc['map']['obstacles'].append((5, 6))
yaml.dump(doc, sys.stdout)
addObstacles()这样你就能得到你想要的东西:
map:
dimensions: [8, 8]
obstacles:
- !!python/tuple [4, 5]
- !!python/tuple [2, 0]
- !!python/tuple [1, 1]
- !!python/tuple [0, 5]
- !!python/tuple [2, 5]
- !!python/tuple [4, 4]
- !!python/tuple [7, 5]
- !!python/tuple [1, 4]
- !!python/tuple [6, 7]
- !!python/tuple [6, 3]
- !!python/tuple [1, 7]
- !!python/tuple [3, 6] # add one after this
- !!python/tuple [5, 6](我在我使用的YAML输入文件中添加了注释)。
发布于 2019-12-22 15:36:58
我不确定你是否真的需要ruamel.yaml。PyYAML提供了您需要的开箱即用功能:
import yaml
def addObstacles():
with open('in.yaml') as f:
doc = yaml.load(f)
doc['map']['obstacles'].append((5, 6))
with open('out.yaml', 'w') as f:
yaml.dump(doc, f)https://stackoverflow.com/questions/59442305
复制相似问题