为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

眼眸繁星 2022-07-26 10:45:33
最近我想用我的 discord.py 机器人更多地使用 YAML 文件。所以我目前正在考虑如何为 YAML 文件中的特定键添加值。这是我当前的 YAML 文件:connected_guilds:     - 1st_guild_id每当它连接到另一个公会时,它应该如下所示:connected_guilds:     - 1st_guild_id     - 2nd_guild_id等等这是我当前的代码:        with open('guilds.yaml', 'r+') as guild_add:             yaml.dump({'connected_guilds'.replace("'", ""): [guild_id]}, guild_add, indent=4)所以基本上我认为我是否应该有一个 if 子句来检查密钥是否已经存在,如果存在,请将其添加到下面,但在实现它时我仍然感到困惑。如果有人可以提供帮助,我将不胜感激!
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

您正在打开,但没有读取文件。您创建一个新列表而不是附加到现有列表。


这是如何做到的:


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()


查看完整回答
反对 回复 2022-07-26
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号