yangmi511

Python 存储数据到json文件

1 前言

很多程序都要求用户输入某种信息,程序一般将信息存储在列表和字典等数据结构中。

用户关闭程序时,就需要将信息进行保存,一种简单的方式是使用模块json来存储数据。

模块json让你能够将简单的Python数据结构转存到文件中,并在程序再次运行时加载该文件中的数据。

还可以使用json在Python程序之间分享数据,更重要的是,JSON(JavaScript Object Notation,最初由JavaScript开发)格式的数据文件能被很多编程语言兼容。

2 使用json.dump( )

实现代码:

1 import json
2 
3 numbers = [1, 3, 5, 7, 11]
4 
5 filename = "numbers.json"
6 with open(filename, \'w\') as file_obj:
7     json.dump(numbers, file_obj)

运行结果:

工作原理:

#1 导入json模块。

#3 定义存储数据的列表。

#5 指定存储数据的文件名称。

#6 以写模式打开存储数据用的文件。

#7 调用json.dump( )存储数据。

3 使用json.load( )

实现代码:

1 import json
2 
3 filename = "numbers.json"
4 with open(filename) as file_obj:
5     numbers = json.load(file_obj)
6 
7 print(numbers) 

运行结果:

工作原理:

#4 只读模式打开文件。

#5 json.load( )加载文件中信息并存储到变量numbers中。

#7 打印numbers中数字信息。

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-01-01
  • 2021-10-10
  • 2022-12-23
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-10
  • 2021-11-26
  • 2021-12-05
  • 2021-12-06
  • 2021-11-17
  • 2021-10-27
相关资源
相似解决方案