一种简单的方式是使用模块json来存储数据,模块json让你能够将简单的Python数据转存在文件中,并在程序再次运行时加载该文件中的数据。你还可以使用json在Python程序之间分享数据。

    JSON(JavaScript Object Notation)格式最初是为JavaScript开发的,但随后成了一种常见的格式,被包括Python在内的众多语言采用。

json.dump()

json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。

import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)

json.load()

json.load()将文件读取到内存中。

import json
filename = 'numbers.json'
with open(filename) as f_obj:
    #加载存储在numbers.json中的信息,并将其存储在变量numbers中
    numbers = json.load(f_obj)
print(numbers)