昨日知识点回顾
导入、读取、改写文件
处理异常(try...except)
今日知识点学习
10.4 存储数据
使用json模块存储共享数据
10.4.1 使用json.dump()和json.load()
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
# import json
# filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
# 运行结果:
# [2, 3, 5, 7, 11, 13]
10.4.2 保存和读取用户生成的数据
import json
user_name = input("Enter your name:")
filename = "username.json"
with open(filename, 'w') as f_obj:
json.dump(user_name, f_obj)
print("We'll remember you when you come back, " + user_name + "!")
with open(filename) as f_obj:
user_name = json.load(f_obj)
print("Welcome back," + user_name + "!")
# 运行结果:
# Enter your name:Eric
# We'll remember you when you come back, Eric!
import json
filename = "username.json"
try:
with open(filename) as f_obj:
user_name = json.load(f_obj)
except:
user_name = input("Enter your name:")
with open(filename, 'w') as f_obj:
json.dump(user_name, f_obj)
print("We'll remember you when you come back, " + user_name + "!")
else:
print("Welcome back," + user_name + "!")
# 运行结果:
# Welcome back,Eric!
10.4.3 重构
#重构前
import json
def greet_user():
"""问候用户,并指出其名字"""
filename = "username.json"
try:
with open(filename) as f_obj:
user_name = json.load(f_obj)
except FileNotFoundError:
user_name = input("Enter your name:")
with open(filename, 'w') as f_obj:
json.dump(user_name, f_obj)
print("We'll remember you when you come back, " + user_name + "!")
else:
print("Welcome back," + user_name + "!")
greet_user()
# 运行结果:
# Welcome back,Eric!
#重构后
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = "username.json"
try:
with open(filename) as f_obj:
user_name = json.load(f_obj)
except FileNotFoundError:
return None
else:
return user_name
def get_new_username():
"""提示用户输入用户名"""
user_name = input("Enter your name:")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(user_name, f_obj)
return user_name
def greet_user():
"""问候用户,并指出其名字"""
user_name = get_stored_username()
if user_name:
print("Welcome back," + user_name + "!")
else:
user_name = get_new_username()
print("We'll remember you when you come back, " + user_name + "!")
greet_user()
# 运行结果:
# Welcome back,Eric!