簡體   English   中英

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

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

我想更新 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)  

這是我想要在我的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]

如何 append 或在.yaml 文件中的先前數據旁邊自動添加新行?

在預期的 output 中,您的根級數據結構是一個序列。 因此,在您的 Python 程序中,您應該從一個空列表開始。 (如果您不知道,最簡單的方法是加載您手工制作的.load文檔,看看它是如何最終成為數據結構 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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM