很多程序都要求用户输入某种信息,程序都把用户提供的信息存储在列表和字典等数据结构中,用户关闭程序时,你几乎总是要保存他们的信息:
一种简单的方式是使用模块json来存储数据(在python中使用json的时候,主要也就是使用json模块,json是以一种良好的格式来进行数据的交互)
模块json能够将简单的Python数据结构转存到文件中,并在程序再次运行时加载该文件中的数据,还可以使用json在Python程序之间分享数据,更重要的是,json数据格式并非Python专用的,这让你能够将以json格式存储的数据与使用其他编程语言的人分享
注意:json(javascriptObject notation)格式最初是为javascript开发的,但随后成了一种常见格式,
被包括python在内的众多语言采用
写入
json_01.py
# _*_ coding:utf-8 _*_
"""
file:json_01.py
date:2018-07-24 5:17 PM
author:wwy
desc:
"""
import json
number = [1,2,3,4]
with open('numbers.json','w') as f_obj:
# 我们使用函数json.dump()将数字列表存储到文件中
json.dump(number,f_obj)
运行结果:
读取
json_02.py
# _*_ coding:utf-8 _*_
"""
file:json_02.py
date:2018-07-28 2:33 PM
author:wwy
desc:
"""
import json
filename = 'numbers.json'
with open(filename) as f_obj:
# 我们使用函数json.load加载存储在numbers.json中的信息
# 并将其存储到变量numbers中
numbers = json.load(f_obj)
print numbers
运行结果:
json_03.py
# _*_ coding:utf-8 _*_
"""
file:json_03.py
date:2018-07-28 2:33 PM
author:wwy
desc:
"""
import json
username = raw_input('what is your name ?')
filename = 'username.json'
with open(filename,'a') as f_obj:
json.dump(username,f_obj)
print 'We will rember you when you come back, %s' % username
运行结果:
json_04.py
# _*_ coding:utf-8 _*_
"""
file:json_04.py
date:2018-07-28 2:33 PM
author:wwy
desc:
"""
import json
filename = "username.json"
with open(filename) as f_obj:
username = json.load(f_obj)
print "Welcome back, %s" % username
运行结果:
json_05.py
# _*_ coding:utf-8 _*_
"""
file:json_05.py
date:2018-07-28 2:33 PM
author:wwy
desc:
"""
import json
filename = "username.json"
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except ValueError:
username = raw_input("What is you name? ")
with open(filename,"w") as f_obj:
json.dump(username,f_obj)
print "We'll remember you when you come back %s" % username
#依赖于try代码块成功执行的代码都应放到else代码块中:
else:
print "Welcome back %s " % username
运行结果: