# -*- coding: utf-8 -*-
from os.path import isfile
class User:
def __init__(self, username, passwd, file_info):
self.user = username
self.pwd = passwd
self.file_db = file_info
def file_oper(file, mode, *args):
if mode == 'a+':
data = args[0]
with open(file, mode) as f:
f.write(data)
elif mode == 'r':
with open(file, mode) as f:
data = f.read()
return data
# 该部分要求实现注册功能,要异常捕获实现注册成功,出错,及用户名已存在提示
def regist(self):
list_user = []
if isfile(self.file_db):
with open(self.file_db, 'r') as f:
for line in f:
username = line.strip().split(':')[0]
list_user.append(username)
if self.user not in list_user:
try:
with open(self.file_db, 'a+') as f:
user_info = '%s:%s\n' %(self.user, self.pwd)
f.write(user_info)
print('\033[32;1m注册成功。\033[0m')
except Exception as e:
print('Error: ', e)
else:
print('\033[31;1m该用户已存在.\033[0m')
def login(self):
list_user = []
u_list = '%s:%s' %(self.user, self.pwd)
with open(self.file_db, 'r') as f:
for line in f:
list_user.append(line.strip())
if u_list in list_user:
print('\033[32;1m登录成功.\033[0m')
else:
print('\033[31;1m用户名或密码错误.\033[0m')
def start():
while True:
print('1. 注册\n'
'2. 登录\n'
'3. 退出')
choice = input('>>>').strip()
if choice.isdigit() and 0 < int(choice) < 4:
if choice == '1':
username = input('用户名:').strip()
passwd = input('密码:').strip()
user = User(username, passwd, 'user.db')
user.regist()
elif choice == '2':
username = input('用户名:').strip()
passwd = input('密码:').strip()
user = User(username, passwd, 'user.db')
user.login()
elif choice == '3':
break
else:
print('输入错误.')
if __name__ == '__main__':
start()
python用户登录注册 文件读写 指针运用
最新推荐文章于 2023-04-06 19:14:32 发布