共計 726 個字符,預計需要花費 2 分鐘才能閱讀完成。
要修改 JSON 文件的內容,可以按照以下步驟進行:
- 使用
json
模塊的load
函數加載 JSON 文件,并將其解析為 Python 對象。例如:
import json
with open('data.json', 'r') as file:
data = json.load(file)
- 對 Python 對象進行修改。你可以像操作任何其他 Python 對象一樣對其進行修改,例如添加、刪除或修改鍵值對。例如:
data['key'] = 'new value'
data.pop('another_key')
- 使用
json
模塊的dump
函數將修改后的 Python 對象重新轉換為 JSON 格式,并將其寫入文件。例如:
with open('data.json', 'w') as file:
json.dump(data, file)
完整的代碼示例:
import json
# 加載 JSON 文件
with open('data.json', 'r') as file:
data = json.load(file)
# 修改數據
data['key'] = 'new value'
data.pop('another_key')
# 保存修改后的數據到 JSON 文件
with open('data.json', 'w') as file:
json.dump(data, file)
請確保將代碼中的 "data.json" 替換為你實際使用的 JSON 文件的路徑。
丸趣 TV 網 – 提供最優質的資源集合!
正文完