# 模拟登录、注册(先创建一个’user_data.txt 文件)
import read_write_file as filefunc
import re
import sys
while True:
print('操作列表:')
print(' 注册 : 1')
print(' 登录 : 2')
print(' 退出 : 3')
print('请输入您的下一步操作序号: ',end='')
operation_num=input()
if operation_num == '1':
print('=============开始注册=============')
print('请输入用户名: ',end='')
user_name = input()
user_data=filefunc.read_data()
while 'name='+user_name in user_data:
print('用户名已存在,请重新输入用户名: ',end='')
user_name=input()
print('请输入密码: ',end='')
password=input()
filefunc.write_new_user(user_name,password)
print('用户注册成功!')
print('=============================')
if operation_num == '2':
name_try_num=1
password_try_num = 1
print('请输入用户名: ', end='')
user_name = input()
user_data = filefunc.read_data()
while 'name='+user_name not in user_data:
if name_try_num < 5:
print('用户名不存在,请重新输入用户名: ',end='')
user_name = input()
name_try_num+=1
else:
print('错误次数过多,程序已退出')
sys.exit(0)
print('请输入密码: ', end='')
password = input()
pattern_password=f'name={user_name}.*?psw=(.*?)\n'
right_password=re.findall(pattern_password,user_data,re.S)[0]
while password!=right_password:
if password_try_num < 5:
print('密码错误,请重新输入密码: ',end='')
password = input()
password_try_num+=1
else:
print('错误次数过多,程序已退出')
sys.exit(0)
print('用户名和密码正确,登录成功')
print('=============================')
if operation_num == '3':
print('程序退出')
break
if operation_num not in('1','2','3'):
print('=============================')
print('指令错误:请重新输入指令')
def read_data():
with open('user_data.txt','r',encoding='utf-8') as f:
reader=f.read()
return reader
def write_new_user(name,psw):
with open('user_data.txt','a',encoding='utf-8') as f:
f.write(f'name={name}\t\t\tpsw={psw}\n')
f.write('================================\n')