当前位置:主页 > 软件编程 > Python代码 >

Python如何存储数据到json文件

时间:2021-04-07 10:10:54 | 栏目:Python代码 | 点击:

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)

运行结果:

工作原理:

3 使用json.load( )

实现代码:

import json
filename = "numbers.json"
with open(filename) as file_obj:
  numbers = json.load(file_obj)
print(numbers)

运行结果:

工作原理:

您可能感兴趣的文章:

相关文章