使用 Python 更改 yaml 文件中的值 [英] Changing a value in a yaml file using Python

查看:145
本文介绍了使用 Python 更改 yaml 文件中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .yaml 文件,我想用 Python 代码更新.假设它看起来像这样:

I have a .yaml file I want to update with a Python code. Let's say it looks something like that:

  state: 'present'

我想要一个代码来改变状态并保存文件.我正在尝试这样的事情但失败了:

I'd like to have a code that changes the state and saves the file. I'm trying with something like this and fail:

def set_state(state):
    with open("file_to_edit.yaml", 'rw') as f:
        doc = yaml.load(f)
    doc['state'] = state
    yaml.dump(f)

我正在使用 Python 的yaml"包.

I am using the 'yaml' package for Python.

推荐答案

问题在于 yaml.dump(doc) 实际上并未写入文件.相反,它将修改后的 YAML 作为字符串返回,除非您也将文件描述符作为参数传递,它允许您直接写入文件.

The problem is that yaml.dump(doc) doesn't actually write to a file. Instead, it returns the modified YAML as a string unless you pass the file descriptor as argument as well, which allows you to write directly to the file.

以下应该有效:

def set_state(state):
    with open('file_to_edit.yaml') as f:
        doc = yaml.load(f)

    doc['state'] = state

    with open('file_to_edit.yaml', 'w') as f:
        yaml.dump(doc, f)

这篇关于使用 Python 更改 yaml 文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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