第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何在 Python 中為 YAML 文件的特定鍵添加值?

如何在 Python 中為 YAML 文件的特定鍵添加值?

眼眸繁星 2022-07-26 10:45:33
最近我想用我的 discord.py 機(jī)器人更多地使用 YAML 文件。所以我目前正在考慮如何為 YAML 文件中的特定鍵添加值。這是我當(dāng)前的 YAML 文件:connected_guilds:     - 1st_guild_id每當(dāng)它連接到另一個(gè)公會(huì)時(shí),它應(yīng)該如下所示:connected_guilds:     - 1st_guild_id     - 2nd_guild_id等等這是我當(dāng)前的代碼:        with open('guilds.yaml', 'r+') as guild_add:             yaml.dump({'connected_guilds'.replace("'", ""): [guild_id]}, guild_add, indent=4)所以基本上我認(rèn)為我是否應(yīng)該有一個(gè) if 子句來(lái)檢查密鑰是否已經(jīng)存在,如果存在,請(qǐng)將其添加到下面,但在實(shí)現(xiàn)它時(shí)我仍然感到困惑。如果有人可以提供幫助,我將不勝感激!
查看完整描述

1 回答

?
慕萊塢森

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊

您正在打開(kāi),但沒(méi)有讀取文件。您創(chuàng)建一個(gè)新列表而不是附加到現(xiàn)有列表。


這是如何做到的:


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


查看完整回答
反對(duì) 回復(fù) 2022-07-26
  • 1 回答
  • 0 關(guān)注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)