# _*_ coding:utf-8 _*_
"""
file: 01.py
date: 2018-07_24 4:39 PM
desc:
很多程序要求用户输入某种信息
程序把用户提供的信息存储在列表和字典等数据结构中
用户关闭程序时你几乎总是要保存他们的信息:
一宗简单的方法是使用模块json来存储数据
(在python中使用json的时候,主要也就是使用json模块,json是一种良好的格式来进行数据的交互)
模块json让你能够将简单的python数据结构转存到文件中
并在程序再次运行时加载该文件中的数据
你还可以使用json在python程序之间分享数据
更重要的是,json数据格式并非python专用的
这让你能够将以json格式存储的数据与使用其他编程语言的人分享
注意:json(java script object notation)格式最初是为javascript开发的,但随后成了一种常见格式,
被包括python在内的众多语言采用
"""
import json
number = [1,2,3,4]
with open('numbers.json','w') as f_obj:
# 我们使用函数json.dump()将数字列表存储到文件中
json.dump(number,f_obj)
# _*_ coding:utf-8 _*_
"""
file: 02.py
date: 2018-07_24 4:41 PM
desc:
"""
import json
filename = 'numbers.json'
with open(filename) as f_obj:
# 我们使用函数json.load加载存储在numbers.json中的信息
#并将其存储在变量numbers中
numbers = json.load(f_obj)
print numbers
# _*_ coding:utf-8 _*_
"""
file: 03.py
date: 2018-07_24 4:56 PM
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 %s' % username
# _*_ coding:utf-8 _*_
"""
file: 04.py
date: 2018-07_24 4:59 PM
desc:
"""
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print 'welcome back,%s' %username
# _*_ coding:utf-8 _*_
"""
file: 05.py
date: 2018-07-24 4:53 PM
author: westos-dd
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