Python 3.4 不从文本文件中读取超过一行
Python 3.4 does not read more than one line from a text file
我正在编写使用基本身份验证的 python(3.4) 代码。我已将凭据(即用户名和密码)存储在文本文件中 (abc.txt)。
每当我登录时,代码只接受文本文件的第一行并忽略其余凭据并给出不正确的凭据错误。
我的代码:
with open('abc.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for username, password in credentials:
user_input = input('Please Enter username: ')
if user_input != username:
sys.exit('Incorrect incorrect username, terminating... \n')
user_input = input('Please Enter Password: ')
if user_input != password:
sys.exit('Incorrect Password, terminating... \n')
print ('User is logged in!\n')
abc.txt:
Sil:xyz123
smith:abc321
发生这种情况是因为您只检查了第一行。目前用户只能输入与文本文件中第一行匹配的凭据,否则程序将退出。您应该使用用户名和密码创建字典,然后检查用户名是否在该字典中,而不是遍历凭据列表。
with open('abc.txt') as f:
credentials = dict([x.strip().split(':') for x in f.readlines()]) # Created a dictionary with username:password items
username_input = input('Please Enter username: ')
if username_input not in credentials: # Check if username is in the credentials dictionary
sys.exit('Incorrect incorrect username, terminating... \n')
password_input = input('Please Enter Password: ')
if password_input != credentials[username_input]: # Check if the password entered matches the password in the dictionary
sys.exit('Incorrect Password, terminating... \n')
print ('User is logged in!\n')
我正在编写使用基本身份验证的 python(3.4) 代码。我已将凭据(即用户名和密码)存储在文本文件中 (abc.txt)。
每当我登录时,代码只接受文本文件的第一行并忽略其余凭据并给出不正确的凭据错误。
我的代码:
with open('abc.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for username, password in credentials:
user_input = input('Please Enter username: ')
if user_input != username:
sys.exit('Incorrect incorrect username, terminating... \n')
user_input = input('Please Enter Password: ')
if user_input != password:
sys.exit('Incorrect Password, terminating... \n')
print ('User is logged in!\n')
abc.txt:
Sil:xyz123
smith:abc321
发生这种情况是因为您只检查了第一行。目前用户只能输入与文本文件中第一行匹配的凭据,否则程序将退出。您应该使用用户名和密码创建字典,然后检查用户名是否在该字典中,而不是遍历凭据列表。
with open('abc.txt') as f:
credentials = dict([x.strip().split(':') for x in f.readlines()]) # Created a dictionary with username:password items
username_input = input('Please Enter username: ')
if username_input not in credentials: # Check if username is in the credentials dictionary
sys.exit('Incorrect incorrect username, terminating... \n')
password_input = input('Please Enter Password: ')
if password_input != credentials[username_input]: # Check if the password entered matches the password in the dictionary
sys.exit('Incorrect Password, terminating... \n')
print ('User is logged in!\n')