json.dump() 存储
导入模块json
以写入模式打开这个文件,让json能够将数据写入其中
我们使用函数json.dump()将数字列表存储到文件numbers.json中
import json
numbers = [1, 3, 5, 7, 9]
filename = 'numbers.json'
with open(filename, 'w') as f_json:
json.dump(numbers, f_json)
json.load() 读取
以读取方式打开这个文件
使用函数json.load()加载存储在numbers.json中的信息,
并将其存储到变量numbers中。最后,我们打印恢复的数字列表,看看它是否与number_writer.py中创建的数字列表相同
with open(filename) as f_json:
numbers2 = json.load(f_json)
print(numbers2)