【发布时间】:2019-12-22 07:09:32
【问题描述】:
我想将元组转储到 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]
【问题讨论】:
标签: python yaml ruamel.yaml