存储数据
很多程序都要求用户输入某种信息,程序把用户提供的信息存储在列表和字典等数据结构中。用户关闭程序时,就要保存提供的信息,一种简单的方式就是使用模块json来存储数据。
模块json能将简单的python数据结构存储到文件中,并在程序再次运转时加载该文件中的数据。还可以使用json在python程序之间分享数据,与使用其他编程语言的人分享。
1. 使用json.dump( )和json.load( )
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'number.json'
with open(filename, 'w') as f_ojb: # 以写入模式打开文件
json.dump(numbers, f_ojb) # 使用函数json.dump()将列表存储到文件中
with open(filename) as f_ojb:
nums = json.load(f_ojb) # 使用函数json.load()将这个列表读取到内存中
print(nums) # 打印读取到内存中的列表,比较是否与存入的列表相同
运行结果:
[2, 3, 5, 7, 11, 13]
相关推荐:《Python视频教程》
2. 保存和读取用户生成的数据
import json
# 存储用户的名字
username = input('What is your name? ')
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj) # 存储用户名与username.json文件中
print("We'll remember you when you come back, " + username + "!")
# 向名字被存储的用户发出问候
with open(filename) as f_obj:
un = json.load(f_obj)
print("nWelcome back, " + un + "!")
运行结果:
What is your name? ela
We'll remember you when you come back, ela!
Welcome back, ela!
优化上述代码:
import json
# 存储用户的名字
username = input('What is your name? ')
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj) # 存储用户名与username.json文件中
print("We'll remember you when you come back, " + username + "!")
# 向名字被存储的用户发出问候
with open(filename) as f_obj:
un = json.load(f_obj)
print("nWelcome back, " + un + "!")
运行结果:
What is your name? ela
We'll remember you when you come back, ela!
Welcome back, ela!
优化上述代码:
import json
# 若存储了用户名就加载;否则提示用户输入并存储
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input('What is your name? ')
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
else:
print("nWelcome back, " + username + "!")
运行结果:
Welcome back, ela!
3. 重构
代码可以运行,但也可以做进一步改进——将代码划分成一些列完成具体工作的函数:这个过程称为重构。
目的:让代码更清晰、易于理解、易扩展。
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""提示用户输入用户名"""
username = input('What is your name? ')
filename = "username.json"
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()