一、需求
1、账号和密码都存在文件里
2、chioce=input ('请输入你的选择:1注册,2删除用户,3登录‘)
3、注册:
输入账号、密码、确认密码
需要校验用户是都存在,两次输入密码是否一致,为空的情况
账号和密码都存在文件里
4、删除:
输入一个用户名
需要交验用户是否存在
5、登录:
输入账号密码
账号密码在文件中存在,登录成功
二、账号密码文件格式
aa,12345 bb,12345 cc,12345
三、初次用列表实现,需要额外的循环
choice = {'1':'注册','2':'删除用户','3':'登录'}#定义字典,可以避免输入‘0’或‘1’以外的选择时报错
#user_chioce input是字符串,如果用int转化非数字的字符串会报错,所以将key定义为字符串‘1’,而非数字1
user_choice = input('请输入你的选择:1,注册2、删除用户3、登录').strip()
if choice.get(user_choice) == '注册': #用get方法,输入key不在字典中不会报错。用chioce[user_choice],输入key不在字典中会报错
user = input('请输入注册用户名').strip()
pwd = input('请输入密码').strip()
cpwd = input('请再次输入密码').strip()
map = []
if user == ''or pwd == '' or cpwd == '':
print('用户名或密码不能为空')
elif pwd != cpwd:
print('两次输入密码不一致')
else:
with open('账号密码',encoding='utf-8') as f:
for line in f:
map.append(line.split(','))
for i in map:
if i.count(user) > 0:
print('用户名已存在')
break
else:
continue
else:
print('注册成功')
with open('账号密码', 'a+', encoding='utf-8') as f: # 以追加读写模式打开文件
str = '{},{}\n'.format(user,pwd)
f.write(str) # 将新用户及密码写入文件
elif choice.get(user_choice) == '删除用户':
user = input('输入要删除的用户名').strip()
map = []
with open('账号密码',encoding='utf-8') as f:#只读模式打开,将文件转化为列表
for line in f:
map.append(line.split(',')) #将账号密码写入列表,map是二维列表
if user == '':
print('账号不能为空')
else:
for i in map:
if i.count(user) > 0:
map.remove(i)
with open('账号密码', 'w', encoding='utf-8') as f: # 将删除用户后的列表写入文件
for i in map:
str = '{},{}\n'.format(i[0],i[1])
f.write(str) # 将用户名密码写入文件
break
else:
continue
else:
print('用户不存在')
elif choice.get(user_choice) == '登录':
user = input('请输入用户名').strip()
pwd = input('请输入密码').strip()
map = [] #定义存放用户名密码的数组
with open('账号密码',encoding='utf-8') as f: #以只读模式打开文件
for line in f:
l = line.strip() #按行取出文件,去掉多余换行符
map.append(l.split(',')) #将账号密码写入列表,map是二维列表
if user == '' or pwd == '':
print('账号密码不能为空')
else:
for i in map: #i为每个账户的用户名密码,是一维列表
if i.count(user) > 0:
if i[0] == user and i[-1] == pwd:
print('登录成功')
else:
print('密码输入错误')
break
else:
continue
else:
print('用户不存在')
else:
print('输入的选择有误')
浙公网安备 33010602011771号