Python编程:利用JSON模块编程验证用户
模块json能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。你还可以使用json在Python程序之间分享数据。
验证一个用户是否是之前的用户?如果是,打印欢迎用户回来,否则,让用户输入正确的用户名。再次运行,输入正确用户名,即可打印输出欢迎信息。
源码如下:
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:
correct = input(f'Are you {username}?(y/n)')
if correct == 'y':
print(f'welcome back , {username}')
else:
username = get_new_username()
print(f'we will remember you when you come back, {username}!')
else:
username = get_new_username()
print(f'we will remember you when you come back, {username}!')
if __name__ == '__main__':
greet_user()