授予Python访问权限

时间:2017-12-04 05:53:35

标签: python

我得到了这个程序并且有效。

#######################################################################
## This program simulates a login screen.
## The username and passwords are stored in an input file.
#######################################################################

f=open('usernames.txt')
usernames=[]
passwords=[]

for index in range(10):
    line = f.readline().strip()
    usernames.append(line)
    line = f.readline().strip()  
    passwords.append(line)

user = input("Username: ")
found = False
for index in range(10):
     if user == usernames[index]:
         found = True
         passwrd = input("Password: ")
         if passwrd == passwords[index]:
             print("Access Granted")
         else :
             print("Username and password do not match")
         break
if (not found):
    print("Username not found")

我需要修改此程序,以便在授予访问权限之前重复询问有效的用户名和密码。我认为这应该是非常简单的,我遇到这么多麻烦的原因是我不明白为什么strip()的调用需要在那里。我不明白程序如何将文本文件的索引与索引后的索引直接匹配。

1 个答案:

答案 0 :(得分:0)

f = open('usernames.txt', 'r')  # you must to setup mode of opening file each time. In this case mode 'r'- read
usernames = []
granted = False

for line in f:
    # read file line by line
    usernames.append(line.strip())

if len(usernames) % 2 != 0:
    # checking that file have even numbers of lines
    print('Bad input file. Last string will be ignored')
    usernames.pop()  # removing of last string

def auth():
    user = input("Username: ")
    try:  # with try we can catch any exceptions
        index = usernames.index(user)   # check that our list have username and get index of it
        if index % 2 != 0:  # checking that it username
            print("Username not found")
            return False
    except:  # if usernames is not contained user string we catch of exception
        print("Username not found")
        return False

    passwrd = input("Password: ")
    if passwrd == usernames[index+1]:
        print("Access Granted")
        return True

    else:
        print("Username and password do not match")
        return False

while not granted:
    granted = auth()