python保存、读取用户生成的数据
python文件操作——保存、读取用户生成的数据
JSON模块
模块json能够将简单的python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据,同时还可以使用jaon在python程序中分享数据。
函数json.dump() 和json.load()
函数json.dump() 接受两个参数:要储存的数据以及可用于存储数据的文件对象。如:
filename = 'aaa.json'
with open(filename, 'w') as f:
json.dump(aaa, f)
函数json.load() 加载存储在 .json 文件中的信息。如:
filename = 'aaa.json'
with open(filename) as f:
aaa = json.load(f)
保存和读取用户生成的数据
import json
# 如果以前存储了用户名,就加载它
# 否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What's 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("Welcome back, " + username + "!")
以上代码重构后:
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = '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 = 'username.json'
with open(filename, 'w') as f:
json.dump(username, f)
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()
运行结果
第一次运行结果:
What is your name? Alice
We'll remember you when you come back, Alice!
Process finished with exit code 0
第二次及多次的运行结果:
Welcome back, Alice!
Process finished with exit code 0
加油!