再添加一个可以查询、修改文件中用户名、密码的代码
时间: 2024-05-15 19:14:25 浏览: 52
以下是一个简单的示例代码,可以查询、修改文件中的用户名和密码。请注意,这只是一个示例,实际应用中需要更多的错误处理和安全性检查。
```python
import csv
def find_user(username, password, filename):
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
if row[0] == username and row[1] == password:
return True
return False
def update_password(username, old_password, new_password, filename):
with open(filename, 'r') as file:
reader = csv.reader(file)
rows = list(reader)
found = False
for i, row in enumerate(rows):
if row[0] == username and row[1] == old_password:
rows[i][1] = new_password
found = True
if not found:
return False
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
return True
```
使用方法:
查询用户:
```python
if find_user('alice', 'password', 'users.csv'):
print('Login successful')
else:
print('Invalid username or password')
```
修改密码:
```python
if update_password('alice', 'password', 'new_password', 'users.csv'):
print('Password updated')
else:
print('User not found or incorrect password')
```
其中,`users.csv` 是包含用户名和密码的 CSV 文件,格式如下:
```
username,password
alice,password
bob,123456
```
阅读全文