【问题标题】:How to add new lines/update data to the yaml file with python?如何使用 python 向 yaml 文件添加新行/更新数据?
【发布时间】:2020-12-29 03:12:14
【问题描述】:

我想更新我的 .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 文件中的先前数据旁边自动追加或添加新行?

【问题讨论】:

  • 尝试在您的open 通话中从write 模式切换到append 模式。相关文档:docs.python.org/3/library/functions.html#open.
  • @n8sty 除非您确切地知道自己在做什么,否则附加到包含 YAML 文档的现有文件不是一个好主意。您最终可能会得到一个无法再加载的文件。

标签: python yaml ruamel.yaml


【解决方案1】:

在预期输出中,您的根级数据结构是一个序列。在你的 因此,您应该从一个空列表开始 Python 程序。 (如果你没有 要知道,最简单的做法是.load 你的 YAML 文档 手工制作,看看它是如何成为 Python 数据结构的。)

您似乎不仅在使用 EOL 的 Python 版本,而且还很旧 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。

【讨论】:

    猜你喜欢
    • 2018-09-20
    • 2016-09-26
    • 2015-04-17
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2021-05-02
    相关资源
    最近更新 更多