python读写json文件详解

在Python中,可以使用json模块来读写JSON格式的文件。下面是一个详细的示例,演示了如何读写JSON文件:

python 复制代码
import json

# 写入JSON文件
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

with open('data.json', 'w') as f:
    json.dump(data, f)

# 读取JSON文件
with open('data.json', 'r') as f:
    loaded_data = json.load(f)
    print(loaded_data)

在这个示例中,首先定义了一个字典data,然后使用json.dump将数据写入到名为data.json的文件中。接着使用json.load读取data.json文件,并将读取的数据加载到loaded_data变量中,最后打印出加载的数据。

相关推荐
Flittly7 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling11 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook15 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风16 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风16 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77392 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm