简体   繁体   English

如何使用 python 向 yaml 文件添加新行/更新数据?

[英]How to add new lines/update data to the yaml file with python?

I want to update my.yaml file and in each iteration new data added to my.yaml file while previous data is still saved, here is piece of my code:我想更新 my.yaml 文件,并在每次迭代中将新数据添加到 my.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)  

and this is my target output result which I want to achieve in my points.yaml file:这是我想要在我的points.yaml文件中实现的目标 output 结果:

- 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]

How to append or add automatically new lines beside previous data in.yaml file?如何 append 或在.yaml 文件中的先前数据旁边自动添加新行?

In the expected output your root level data structure is a sequence.在预期的 output 中,您的根级数据结构是一个序列。 In your Python program you should therefor start with an empty list.因此,在您的 Python 程序中,您应该从一个空列表开始。 (In case you didn't know that, the easiest thing to do is .load the YAML document that you hand-crafted and see how it ends up as data structure Python.) (如果您不知道,最简单的方法是加载您手工制作的.load文档,看看它是如何最终成为数据结构 Python 的。)

Not only do you seem to be using a version of Python that is EOL, but also old (compatibility) routines for ruamel.yaml.您似乎不仅使用的是 EOL 的 Python 版本,而且还使用了 ruamel.yaml 的旧(兼容性)例程。 If you cannot change the former, at least start using the new ruamel.yaml API:如果不能改变前者,至少开始使用新的 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())

which gives:这使:

- 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]

Please note that I changed the argument to range() to 5.请注意,我将range()的参数更改为 5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM