Python3 - 在 yaml 中写回相同的流 [英] Python3 - write back to same stream in yaml

查看:32
本文介绍了Python3 - 在 yaml 中写回相同的流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:有一个包含多个流的 yaml 文件.我想将键/值附加到单个流.然后将添加内容(包括原始其他流)写回文件.

Goal: There is a yaml file with multiple streams. I want to append a key/value to a single stream. Then write the addition, including the original other streams, back into the file.

示例:

file.yaml 包含:

file.yaml contains:

---
one_key: value
---
kind: Deployment
appendhere:
  subkey: subvaluekey
---
third_key: value

现在,运行 python 脚本应该按照需要的输出运行:

Now, run the python script should run with this as desired output:

---
one_key: value
---
kind: Deployment
appendhere:
  subkey: subvaluekey
  alright: value
---
third_key: value

我的代码:我可以将子键附加到流中.

My code: I can append the subkey to the stream.

#!/usr/bin/env python3
import yaml

stream = open('file.yaml', 'r')
for data in yaml.load_all(stream, Loader=yaml.FullLoader):
  for k, v in data.items():
    if "kind" in k:
      if "Deployment" in v:
          data['appendhere'].update({'addedkey': {'alright', 'value'}})

我不知道如何编写 Python 来写回 file.yaml ;通过保留其他原始流,以及我附加了一个键的流.

I don’t know how to program Python to write back into file.yaml ; by keeping the other original streams, and the stream I appended a key to.

推荐答案

你需要把已读过的文档列表存放在某个地方,以便你可以再次转储:

You need to store the read list of documents somewhere so that you can dump it again:

with open('file.yaml', 'r+') as stream:
  documents = list(yaml.load_all(stream, Loader=yaml.FullLoader))
  for data in documents:
    # [snip] modification code
  # move position in stream to front
  stream.seek(0)
  yaml.dump_all(documents, stream)
  # discards surplus content when new data is smaller than old data
  stream.truncate()

这篇关于Python3 - 在 yaml 中写回相同的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆