我想更新我的.yaml文件,并在每次迭代中添加到我的.yaml文件中,而以前的数据还在保存中,下面是我的代码:
import yaml
num=0
for i in range(4):
num +=1
data_yaml =[{"name" : num, "point" : [x, y , z]}]
with open('points.yaml', 'w') as yaml_file:
yaml.dump(data_yaml, yaml_file)
这是我想在points.yaml文件中实现的目标输出结果:
- name: 1
point: [0.7, -0.2, 0.22]
- name: 2
point: [0.6, -0.11, 0.8]
- name: 3
point: [0.4, -0.2, 0.6]
- name: 4
point: [0.3, -0.7, 0.8]
- name: 5
point: [0.1, -0.4, 0.2]
如何在.yaml文件中添加或自动添加以前的数据之外的新行?
发布于 2020-12-29 07:04:11
在预期的输出中,根级数据结构是一个序列。在Python程序中,应该从空列表开始。(如果您不知道这一点,那么最简单的方法就是手工构建的YAML文档.load
,看看它是如何作为数据结构Python的。)
您不仅使用了Python版本的EOL,而且还使用了ruamel.yaml的旧(兼容性)例程。如果无法更改前者,至少开始使用新的ruamel.yaml API:
from __future__ import print_function
import sys
import ruamel.yaml
points = [
[0.7, -0.2, 0.22],
[0.6, -0.11, 0.8],
[0.4, -0.2, 0.6],
[0.3, -0.7, 0.8],
[0.1, -0.4, 0.2],
]
data = []
yaml = ruamel.yaml.YAML(typ='safe')
num=0
for i in range(5):
num +=1
x, y, z = points[i]
data.append({"name" : num,
"point" : [x, y , z ]
})
with open('points.yaml', 'w') as yaml_file:
yaml.dump(data, yaml_file)
with open('points.yaml') as yaml_file:
print(yaml_file.read())
这意味着:
- name: 1
point: [0.7, -0.2, 0.22]
- name: 2
point: [0.6, -0.11, 0.8]
- name: 3
point: [0.4, -0.2, 0.6]
- name: 4
point: [0.3, -0.7, 0.8]
- name: 5
point: [0.1, -0.4, 0.2]
请注意,我将参数更改为range()
为5。
https://stackoverflow.com/questions/65486875
复制相似问题