【问题标题】:Python 3.4 does not read more than one line from a text filePython 3.4 不会从文本文件中读取超过一行
【发布时间】:2016-10-06 09:17:50
【问题描述】:

我正在编写一个使用基本身份验证的 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

【问题讨论】:

  • 请为您的问题使用更具体的标题。

标签: python python-3.4


【解决方案1】:

这是因为您只检查第一行。目前用户只能在文本文件中输入与第一行匹配的凭据,否则程序将退出。您应该使用用户名和密码创建一个字典,然后检查用户名是否在该字典中,而不是遍历凭据列表。

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')  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    相关资源
    最近更新 更多