Python如何存储数据到json文件
作者:躬耕南阳 时间:2023-11-24 14:31:12
1 前言
很多程序都要求用户输入某种信息,程序一般将信息存储在列表和字典等数据结构中。
用户关闭程序时,就需要将信息进行保存,一种简单的方式是使用模块json来存储数据。
模块json让你能够将简单的Python数据结构转存到文件中,并在程序再次运行时加载该文件中的数据。
还可以使用json在Python程序之间分享数据,更重要的是,JSON(JavaScript Object Notation,最初由JavaScript开发)格式的数据文件能被很多编程语言兼容。
2 使用json.dump( )
实现代码:
import json
numbers = [1, 3, 5, 7, 11]
filename = "numbers.json"
with open(filename, 'w') as file_obj:
json.dump(numbers, file_obj)
运行结果:
工作原理:
导入json模块。
定义存储数据的列表。
指定存储数据的文件名称。
以写模式打开存储数据用的文件。
调用json.dump( )存储数据。
3 使用json.load( )
实现代码:
import json
filename = "numbers.json"
with open(filename) as file_obj:
numbers = json.load(file_obj)
print(numbers)
运行结果:
工作原理:
只读模式打开文件。
json.load( )加载文件中信息并存储到变量numbers中。
打印numbers中数字信息。
来源:https://www.cnblogs.com/yangmi511/p/12442899.html
标签:Python,存储,数据,json
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
原生js+ajax分页组件
2024-05-21 10:12:06
从django的中间件直接返回请求的方法
2022-02-04 23:32:23
解析:Perl下应当如何连接Access数据库
2008-11-28 16:40:00
Python实战使用Selenium爬取网页数据
2021-06-18 19:11:56
Go语言操作Excel利器之excelize类库详解
2024-04-28 09:12:47
pandas.dataframe按行索引表达式选取方法
2021-10-28 20:26:32
Python利用PaddleOCR制作个搜题小工具
2022-07-22 16:18:18
![](https://img.aspxhome.com/file/2023/4/68974_0s.jpg)
python保存字典数据到csv文件的完整代码
2023-04-09 17:02:02
![](https://img.aspxhome.com/file/2023/7/101307_0s.png)
Python 函数基础知识汇总
2021-12-22 15:47:09
Python3以GitHub为例来实现模拟登录和爬取的实例讲解
2022-01-17 14:52:02
![](https://img.aspxhome.com/file/2023/5/85075_0s.png)
C#连接Oracle数据库的多种方法总结
2024-01-23 12:43:45
![](https://img.aspxhome.com/file/2023/9/66109_0s.png)
Python txt文件加入字典并查询的方法
2021-11-09 12:50:15
Python错误的处理方法
2021-08-01 05:38:15
![](https://img.aspxhome.com/file/2023/9/105189_0s.png)
费茨法则在交互设计中的应用
2009-07-09 19:02:00
![](https://img.aspxhome.com/file/UploadPic/20097/9/01-64s.gif)
zabbix监控Nginx/Tomcat/MySQL的详细教程
2024-01-15 04:31:33
![](https://img.aspxhome.com/file/2023/3/93893_0s.png)
python 实现二维列表转置
2021-04-20 10:00:06
在Python中使用AOP实现Redis缓存示例
2021-09-12 11:18:45
python在不同条件下的输入与输出
2021-10-20 05:51:37
js实现遮罩层弹出框的方法
2024-02-23 09:01:33
用python3 urllib破解有道翻译反爬虫机制详解
2022-05-27 00:23:07
![](https://img.aspxhome.com/file/2023/0/70210_0s.png)