简体   繁体   English

如何在 Python 中为 YAML 文件的特定键添加值?

[英]How can I add a value to a specific key to a YAML file in Python?

Recently I would like to work with YAML file even more with my discord.py bot.最近我想用我的 discord.py 机器人更多地使用 YAML 文件。 So I am currently thinking how do I add a value to a specific key in a YAML file.所以我目前正在考虑如何向 YAML 文件中的特定键添加值。 This is my current YAML file:这是我当前的 YAML 文件:

connected_guilds:
    - 1st_guild_id

And whenever it connects to another guild, it should appears like so:每当它连接到另一个公会时,它应该看起来像这样:

connected_guilds:
    - 1st_guild_id
    - 2nd_guild_id

etc.等等。

Here is my current code:这是我当前的代码:

        with open('guilds.yaml', 'r+') as guild_add:
            yaml.dump({'connected_guilds'.replace("'", ""): [guild_id]}, guild_add, indent=4)

So basically I think if I should have an if-clause checking if the key already exists and if so, add it below but I'm still confused while implementing that.所以基本上我认为我是否应该有一个 if 子句检查密钥是否已经存在,如果存在,请将其添加到下面,但在实现它时我仍然感到困惑。

I'd be grateful if someone can help!如果有人可以提供帮助,我将不胜感激!

You are opening, but not reading the file.您正在打开,但未读取文件。 You create a new list instead of appending to the existing list.您创建一个新列表而不是附加到现有列表。

Here's how to do it:这是如何做到的:

with open('guilds.yaml', 'r+') as f:
  # load the content
  content = yaml.safe_load(f)
  # append the new id to the existing list
  content["connected_guilds"].append(guild_id)
  # reset the position in the file (it's at the end since we read the file)
  f.seek(0)
  # write the updated YAML to the file
  yaml.dump(content, f)
  # throw away any (old) content of the file after the current position,
  # which is at the end of the YAML we just wrote.
  # since we added more content, it's unlikely that there is more content here,
  # but not impossible!
  f.truncate()

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

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