Python 存储数据
使用json.dump()和json.load()
- 先导入模块json,创建一个数字列表
- 使用文件扩展名 .json 来指出文件存储的数据为 JSON 格式
- 函数json.dump()接受两个实参:要存储的数据以及可用于存储的文件对象
# 案例:编写一个存储一组数字的简短程序,再编写一个将这些数字读取到内存中的程序,
# 第一个程序使用json.dump()来存储这组数字,第二个程序将使用json.load().
#先导入模块json
import json
numbers = [2,3,5,7,11,13]
# 使用文件扩展名 .json 来指出文件存储的数据为 JSON 格式
filename = 'numbers.json'
# 以写入模式打开这个文件,让 json 能够将数据写入其中
with open(filename,'w') as f:
json.dump(numbers,f)
# 使用函数json.dump()将数字列表存储到文件numbers.json中
import json
filename = 'numbers.json'
with open(filename) as f:
numbers = json.load(f)
# 使函数加载存储在json中的信息
print(numbers)
[2, 3, 5, 7, 11, 13]
保存和读取用户生成的数据
# 案例:存储用户的名字:
import json
username = input("What is your name? ")
filename = 'username.json'
with open(filename,'w') as f:
json.dump(username,f)
print("We'll remember you when you come back, " + username + '!')
What is your name? yege
We'll remember you when you come back, yege!
# 编写一个程序,向其名字被存储的用户发出问候:
# 使用json.load() 将存储在json中的信息读取到变量username中
import json
filename = 'username.json'
with open(filename) as f:
username = json.load(f)
print("Welocm back," + username + "!")
Welocm back,yege!
import json
filename = 'name.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name ?")
with open(filename,'w') as f:
json.dump(username,f)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcom back, " + username + "!")
What is your name ?yege
We'll remember you when you come back, yege!
import json
filename = 'name.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name ?")
with open(filename,'w') as f:
json.dump(username,f)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcom back, " + username + "!")
Welcom back, yege!
重构
- 将代码划分为一系列完成具体工作的函数
# 重构上面案例
import json
def greet_user():
'''问候用户,并指出其名字'''
filename = 'name.json'
try:
with open(filename) as f:
name = json.load(f)
except FileNotFoundError:
name = input("What is your name ?")
with open(filename,'w') as f:
json.dump(name,f)
print("We'll remembe you come bace, " + name + "!")
else:
print("Welcome back, " + name + "!")
greet_user()
What is your name ?qi tian da sheng sun wu kong
We'll remembe you come bace, qi tian da sheng sun wu kong!
import json
def greet_user():
'''问候用户,并指出其名字'''
filename = 'name.json'
try:
with open(filename) as f:
name = json.load(f)
except FileNotFoundError:
name = input("What is your name ?")
with open(filename,'w') as f:
json.dump(name,f)
print("We'll remembe you come bace, " + name + "!")
else:
print("Welcome back, " + name + "!")
greet_user()
Welcome back, qi tian da sheng sun wu kong!
# 重构,每个函数执行单一而清晰的任务
import json
def get_stored_name():
'''如果存储了用户名,就获取它'''
filename = 'name.json'
try:
with open(filename) as f:
name = json.load(f)
except FileNotFoundError:
return None
else:
return name
def get_new_name():
'''提示用户输入用户名'''
name = input("What's your name? ")
filename = 'name.json'
with open(filename,'w') as f:
json.dump(name,f)
return name
def greet_user():
'''问候用户,并指出其名字'''
name = get_stored_name()
if name :
print("Welcom back, " + name + "!")
else:
name = get_new_name()
print("We'll remember you when you come back, " + username + "!")
greet_user()
Welcom back, qi tian da sheng sun wu kong!
练习
1.喜欢的数字:
- 编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中,再编写一个程序,从文件中读取这个值,并打印消息“I konw your favorite number! It’s____”
import json
filename = 'number.json'
number = input("我喜欢的数字是?")
with open(filename,'w') as f:
json.dump(number,f)
print("Thanks! I'll remember that.")
我喜欢的数字是?66
Thanks! I'll remember that.
import json
filename = 'number.json'
with open(filename) as f:
numbers = json.load(f)
print("I know your favorite number! It's " + numbers + "!")
I know your favorite number! It's 66!
2.记住喜欢的数字
- 将练习1中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。
import json
filename = 'number.json'
try:
with open(filename) as f:
numbers = json.load(f)
except FileNotFoundError:
print("该文件不存在,正在创建,请稍等!")
number = input("我喜欢的数字是? ")
with open(filename,'w') as f:
numbers = json.dump(number,f)
else:
print("I know your favorite number! It's " + number + "!")
该文件不存在,正在创建,请稍等!
我喜欢的数字是? 34
import json
filename = 'number.json'
try:
with open(filename) as f:
numbers = json.load(f)
except FileNotFoundError:
print("该文件不存在,正在创建,请稍等!")
number = input("我喜欢的数字是? ")
with open(filename,'w') as f:
numbers = json.dump(number,f)
else:
print("I know your favorite number! It's " + number + " !")
I know your favorite number! It's 34 !
- 验证用户
- 在前面的案例中假设用户自己已输入用户名,要么是首次运行该程序,修改这个程序,应对这样的情形:当前和最后一次运行程序的用户并非同一个人。再greet()中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username(),让用户输入正确的用户名
# 原代码:
import json
def get_stored_name():
'''如果存储了用户名,就获取它'''
filename = 'name.json'
try:
with open(filename) as f:
name = json.load(f)
except FileNotFoundError:
return None
else:
return name
def get_new_name():
'''提示用户输入用户名'''
name = input("What's your name? ")
filename = 'name.json'
with open(filename,'w') as f:
json.dump(name,f)
return name
def greet_user():
'''问候用户,并指出其名字'''
name = get_stored_name()
if name :
print("Welcom back, " + name + "!")
else:
name = get_new_name()
print("We'll remember you when you come back, " + username + "!")
greet_user()
# 修改代码:-----第一次运行,无name.json文件
import json
def get_stored_name():
'''如果存储了用户名,就获取它'''
filename = 'name.json'
try:
with open(filename) as f:
name = json.load(f)
except FileNotFoundError:
return None
else:
return name
def get_new_name():
'''提示用户输入用户名'''
name = input("What's your name? ")
filename = 'name.json'
with open(filename,'w') as f:
json.dump(name,f)
return name
def greet_user():
'''问候用户,并指出其名字'''
name = get_stored_name()
if name :
choose = input("The name is yours? (YES/NO)")
if choose == 'YES':
print("Welcom back, " + name + "!")
else:
print("Please! Write The True name.")
name = get_new_name()
else:
name = get_new_name()
print("We'll remember you when you come back, " + name + "!")
greet_user()
What's your name? YeGeLi
We'll remember you when you come back, YeGeLi!
# 修改代码:-----第二次运行,确认用户,并添加用户
import json
def get_stored_name():
'''如果存储了用户名,就获取它'''
filename = 'name.json'
try:
with open(filename) as f:
name = json.load(f)
except FileNotFoundError:
return None
else:
return name
def get_new_name():
'''提示用户输入用户名'''
name = input("What's your name? ")
filename = 'name.json'
with open(filename,'w') as f:
json.dump(name,f)
return name
def greet_user():
'''问候用户,并指出其名字'''
name = get_stored_name()
if name :
choose = input("The name is yours? (YES/NO)")
if choose == 'YES':
print("Welcom back, " + name + "!")
else:
print("Please! Write The True name.")
name = get_new_name()
else:
name = get_new_name()
print("We'll remember you when you come back, " + name + "!")
greet_user()
The name is yours? (YES/NO)YES
Welcom back, YeGeLi!