一:目的:
存在用户登录三次,三次后登录失败退出登录,如果账号不存在,就注册新用户到db文件里
DB_FILE = 'db'
def login(dbfile):
count = 1
while count <= 3:
print('登录尝试第{}次'.format(count))
user_name = input('请输入用户名:')
password = input('请输入密码:')
with open(dbfile, mode='r', encoding='utf-8') as f:
for line in f:
if user_name in line:
# 这里只有当登录用户存在db文件,获取,如果放在上面,如果db文件是空的,就会报错,注意这点
account = line.split(',')[0].strip()
passwd = line.split(',')[1].strip()
if account == user_name.strip() and password.strip() == passwd:
print('登录成功')
return True
else:
print('账号或者密码输入错误')
count += 1
break
# 上面for对db文件循环完了,未发现登录的账号存在,就调用注册,这里需要注意的
else:
print('{}账号是新用户'.format(user_name))
return register(user_name, password, dbfile)
def register(user_name, password, dbfile):
print('{}账号注册'.format(user_name))
with open(dbfile, mode='a', encoding='utf-8') as f:
f.write('{},{}\n'.format(user_name, password))
def run():
return login(DB_FILE)
if __name__ == '__main__':
run()