存储数据
模块json可以将简单的Python数据转存到文件中,并在程序再次运行时加载该文件的数据
json = JavaScript object notation
使用json.dump :
函数json.dump接受两个实参,要存储的数据,以及可用于存储数据的文件对象。
演示如下:
import json
numbers = [2,3,5,7,11,13]
filename = 'text_files/numbers.json'
with open(filename,'w') as f:
json.dump(numbers,f)
会在指定的文件夹中新建这个numbers.json的文件,打开后
[2, 3, 5, 7, 11, 13]
再编写程序,使用json.load() 将列表读取到内存中
filename = 'text_files/numbers.json'
with open(filename) as f:
numbers = json.load(f)
print(numbers)
[2, 3, 5, 7, 11, 13]
[Finished in 78ms]
存储用户的名字:
import json
username = input("What is your name? ")
filename = 'text_files/username.json'
with open(filename,'w') as f:
json.dump(username,f)
print(f"We'll remenber you when you come back, {username}")
打开json文件后是如此内容
"melong"
再来编写另一个程序,向已存储了名字的用户发出问候:
import json
filename = 'text_files/username.json'
with open(filename) as f:
username = json.load(f)
print(f"Welcome back, {username}")
执行之后
Welcome back, melong
[Finished in 62ms]
将上述两个程序合并,变成“组合拳”
编写一个尝试恢复用户名的try代码块。如果文件不存在,就在except代码块中提示用户输入用户名,并将其存储在username.json文件中,再次运行时可以
import json
filename = 'text_files/username.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(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {username}! ")
第一次执行结果
X:\Python\Python38\python.exe X:\python_work\test.py
What is your name? xiaoming
We'll remember you when you come back, xiaoming!
Process finished with exit code 0
第二次及以后执行都显示
X:\Python\Python38\python.exe X:\python_work\test.py
Welcome back, xiaoming!
Process finished with exit code 0
尝试打开username.json,因为不存在,所以先在except中创建,引发了FileNotFoundError,创建了用户后,再次执行就是
第二次的结果
重构:
将代码通过将一些列完成具体工作的函数,进行改进并实现,称之为重构
让代码更清晰、易于理解、容易扩展
import json
def greet_user():
"""问候用户,并指出其名字"""
filename = 'text_files/username.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(f"We'll remember you when you come back,{username}")
else:
print(f"Welcome back, {username}!")
greet_user()
执行之后,由于上述文件及内容存在,所以结论是
Welcome back, xiaoming!
[Finished in 62ms]
将获取已存储用户名的代码转移到另一个函数中,减少greet_user的任务量
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'text_files/username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print(f"Welcome back, {username}")
else:
username = input("What is your name? ")
filename = 'text_files/username.json'
with open(filename,'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}")
greet_user()
如果文件username.json不存在,就返回None,这让我们能够使用函数的返回值做简单的测试。
如果成功地获取了用户名,就打印一条欢迎用户回来的消息,否则提示用户输入用户名。
再重构greet_user()中的另一个代码块
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'text_files/username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""提示用户输入用户名"""
username = input("What is your name? ")
filename = 'text_files/username.json'
with open(filename,'w') as f:
json.dump(username,f)
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print(f"Welcome back, {username}")
else:
username = get_new_username
filename = 'text_files/username.json'
print(f"We'll remember you when you come back, {username}")
greet_user()
在这个最终版本中,每个函数都执行单一而清晰的任务
最后在必要时调用get_new_username() ,
该函数只负责获取并存储新用户的用户名。要编写出清晰而易于维
护和扩展的代码,这种划分必不可少。