#python3.7-PyCharm 解释器
1、提示用户输入用户名: 关于python的file读写操作请参见教程python3的file方法 用户输入用户名后台到用户名列表"name_init"文件检查用户名是否存在,若存在,则检查用户是否被锁定,进行步骤2;若不存在,提示用户注册,输入密码和确认密码(密码不一致,提示错误),一致后将用户名写入"name_init"文件,同时将用户名密码以“用户名:密码”方式写入“name_password_init”文件,提示注册成功,然后成功登陆,见图1-1:
2、检查用户是否被锁定:若锁定,则提示已被锁定联系管理员,见图1-2;若未被锁定,则提示用户输入密码,进行步骤3.
3、提示用户输入密码:若密码正确,则提示登陆成功,见图1-3;若不正确,则允许输入n次,第n-1次时提示只有最后一次机会,连续错了n次后,账户被锁定,用户名被写入"locked_namelist",见下图,例子中n=3.
图1-3 成功登陆
图1-4 用户名被锁定
4、下面为源码:
__author__ = 'Administrator'
username = input("username:")
#print(username)
name_list = open('name_init','r+') #'name_init' file created before running
name_text = name_list.readlines()
#print(name_text)
username_i = username+'\n'
if username_i not in name_text :
print("User doesn't exist,please register.")
continue_confirm = input("Do you want to register?...Y/N:")
if continue_confirm == "n" or continue_confirm == "N":
print("You are leaving.")
else:
password1 = input("Input the password:")
confirm_password = input("Confirm the password:")
if password1 == confirm_password :
name_w = username + '\n'
name_list.write(name_w)
name_list.close()
n_p = username + ':'+password1+'\n'
name_l_f = open('name_password_init','a+') #'name_password_init' file created before running
name_l_f.write(n_p)
name_l_f.close()
print("Registration success\n","Welcome user---{name}---login...".format(name=username))
else:
print('Incorrect input.')
else:
locked_f = open("locked_namelist",'r+')
locked_list = locked_f.readlines()
if username+'\n' in locked_list :
locked_f.close()
print('You are locked,please contact the administrator for unlock')
else:
count = 0
ct_l = 3
name_l_f = open('name_password_init','r+') #'name_password_init' file created before running
namelist_f = name_l_f.readlines()
while count
password = input("password:")
user_info = username+':'+password+'\n'
if user_info in namelist_f :
print("Welcome user---{name}---login...".format(name=username))
break
else :
if count < ct_l-2:
print('Incorrect passed,please try again.')
elif count == ct_l-2 :
print('Warning:Only one chance left.')
count += 1
if count == ct_l :
locked_f.write(username+'\n')
locked_f.close()
print('The username was locked,please contact the administrator.')
name_l_f.close()
第23行的文件打开模式为'a+',主要为了写入,指针定位到文件的末尾: name_l_f = open('name_password_init','a+') 第40行的文件打开模式为'r+',需要先读取文件,指针从文件开头开始: name_l_f = open('name_password_init','r+') file.readlines()读取文件的所有内容,读取的结果为列表格式,结果中带有换行符‘\n’,所以文件写入时也需要带上‘\n’,便于提取文件内容。