Python練習#7-載入json指令修改文件內容

by Gemma

本周目標

熟悉Python的基礎語法與資料結構

任務

  • 學習函數的定義和使用(Parameters、Return Values)
  • 練習設計和使用函數,並完成更多字串處理練習(例如文字查找和替換)
  • 學習file open, write, read指令
  • 學習json指令

專案練習

載入json檔案更新內容後重新回傳文字

import json
with open("1112config.json",mode="r") as file:
    data=json.load(file)
    # print(data)
data["name"]="Will"
data["version"]="2.3.7"
with open("1112config.json",mode="w") as file:
    data=json.dump(data,file)
with open("1112config.json",mode="r") as file:
    data=json.load(file)
print("Name:",data["name"])
print("Version:",data["version"])

Output

json原資料

{
    "name":"Steve",
    "version":"1.2.3"
}

程式回傳文字並更新

{"name": "Will", "version": "2.3.7"}

You may also like

Leave a Comment