python中,实现登录功能,要求用户名和密码存储在文件中,要求可以动态添加用户名和密码(增加,删除,修改,查看)
时间: 2024-10-16 07:11:25 浏览: 15
在Python中,我们可以使用字典数据结构来模拟一个简单的用户数据库,存储用户名和对应的密码,同时提供增删改查的功能。这里有一个基础的示例:
```python
class UserDatabase:
def __init__(self, filename='users.txt'):
self.filename = filename
self.data = {} # 字典用于存储用户信息
def read_data(self):
if os.path.isfile(self.filename):
with open(self.filename, 'r') as file:
for line in file:
username, password = line.strip().split(':')
self.data[username] = password
else:
self.data = {}
def add_user(self, username, password):
self.read_data()
self.data[username] = password
with open(self.filename, 'w') as file:
for user, pwd in self.data.items():
file.write(f'{user}:{pwd}\n')
def remove_user(self, username):
self.read_data()
if username in self.data:
del self.data[username]
with open(self.filename, 'w') as file:
for user, pwd in self.data.items():
file.write(f'{user}:{pwd}\n')
else:
print(f"No user found with the name '{username}'.")
def update_password(self, username, new_password):
self.read_data()
if username in self.data:
self.data[username] = new_password
with open(self.filename, 'w') as file:
for user, pwd in self.data.items():
file.write(f'{user}:{pwd}\n')
else:
print(f"No user found with the name '{username}'.")
def view_users(self):
self.read_data()
if self.data:
print("Users:")
for username, password in self.data.items():
print(f"{username}: {('*' * len(password))[:8]} (hidden)")
else:
print("No users in database.")
# 使用示例
db = UserDatabase()
db.add_user('user1', 'password1')
db.view_users()
db.update_password('user1', 'new_password1')
db.remove_user('user1')
```
这个类首先检查文件是否存在,然后读取或初始化空的数据。每个操作结束后都会更新文件内容。请注意,为了安全考虑,实际生产环境中不应直接在明文中存储密码,而应使用加密技术。
阅读全文