亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號