python 注册登录(文件操作)
name = input("请注册用户:") password = input("请注册密码:") with open(file="user", mode='w', encoding='utf-8') as f: f.write('{}\n{}'.format(name, password)) # 将用户、密码写入文件 print("恭喜%s,注册成功!" % name) count = 0 li = [] while count < 3: # 三次输入机会 _name = input("请输入用户:") _password = input("请输入密码:") with open(file='user', mode='r+', encoding='utf-8') as f: # 读取文件 for line in f: #li.append(line) if li[0].strip() == _name and li[1].strip() == _password: print("登录成功!") break else: print("请重新输入!") if count == 2: print("笨蛋,回家养猪去吧!!!!!") count += 1
# 改良
name = input("请注册用户:") password = input("请注册密码:") with open(file="{}".format(name), mode='w', encoding='utf-8') as f: f.write('{}\n{}'.format(name, password)) print("恭喜%s,注册成功!" % name) count = 0 # li = [] while count < 3: _name = input("请输入用户:") _password = input("请输入密码:") with open(file="{}".format(name), mode='r+', encoding='utf-8') as f: # for line in f: # li.append(line) li = f.readlines() if li[0].strip() == _name and li[1].strip() == _password: print("登录成功!") break else: print("请重新输入!") if count == 2: print("笨蛋,回家养猪去吧!!!!!") count += 1
过程
1)用户交互-注册用户、密码
2)写入文件
3)while循环,3次机会
4)用户交互-输入用户、密码
5)读文件
6)str比较