filename = 'username.json' try: with open(filename) as file_obj: username = json.load(file_obj) except FileNotFoundError: username = input("请输入用户名:") with open(filename, 'w') as file_obj: json.dump(username, file_obj) print("We will remember you when you come back, " + username + "!") else: print("Welcome back, " + username + "!")
json.dump()用于创建文件(json格式)并向文件中写入信息
json.load()用于加载文件(json格式)中已有信息
重构之后的代码:
def get_stored_username(): file="username.json" try: with open(file) as f_obj: username=json.load(f_obj) except FileNotFoundError : return None else: return username def get_new_username(): file="username.json" with open(file, 'w') as f_obj: username=input("please input your username: ") json.dump(username, f_obj) def greet_users(): username=get_stored_username() if username: print("Welcome back, " + username + "!") else: username=get_new_username() print("We will remember you when you come back, " + username + "!") greet_users()
判断目前用户与之前用户是否为同一个人,如果不是,请重新输入用户名。
def get_stored_username(): file="username.json" try: with open(file) as f_obj: username=json.load(f_obj) except FileNotFoundError: return None else: return username def get_new_username(): file="username.json" with open(file, 'w') as f_obj: username=input("please input your username: ") json.dump(username, f_obj) def greet_users(): username=get_stored_username() if username: print("The present user's username is " + username) answer=input("Is it your username?") if answer=='y': print("Welcome back, " + username + "!") if answer=='n': get_new_username() username = get_stored_username() print("We will remember you when you come back, " + str(username) + "!") else: get_new_username() username = get_stored_username() print("We will remember you when you come back, " + str(username) + "!") greet_users()