您的基本问题是您的文件中有[ ]围绕用户名和密码组合,但您无法解释这一点。在
您的代码还有一些其他风格问题,以下是经过编辑的版本:import getpass
from time import sleep
password_file = r'C:\....\Database.txt'
def login(user,passwd):
''' Checks the credentials of a user '''
with open(password_file) as f:
for line in f:
if line.strip(): # skips blank lines
username,password = line.split(',') # this gets the individual parts
username = username[1:] # gets rid of the [
password = password[:-1] # the same for the password
if user == username and password == passwd:
return True
return False
if __name__ == '__main__':
username = input('Please enter the username: ')
passwd = getpass('Please enter the password: ')
if login(user,passwd):
print('Welcome {1}'.format(user))
sleep(3)
else:
print('Failed! Mwahahaha!!')
sleep(5)
首先,您不需要()来“初始化”变量;更重要的是在Python中根本不需要初始化变量。这是因为Python没有变量,而是有指向事物的名称。在
接下来,python style guide表示变量名和方法名应该是小写的。在
现在-代码的主要部分:
^{pr2}$
我使用split()将行分解为用户名和密码部分;但是正如您所见,[仍然把事情搞砸了。接下来我做了这个:>>> username[1:]
'username'
>>> password[:-1]
'sekret'
它使用slice notation来去除前导字符和结尾字符,去掉[ ]。在
这些线条:with open(password_file) as f: # 1
for line in f: # 2
if line.strip(): # skips blank lines
执行以下操作:{/ema>打开文件
这个for循环遍历f中的每一行,并为文件中的每一行指定名称line。
第三部分确保我们跳过空行。strip()将删除所有不可打印的字符;因此,如果没有剩余字符,则该行为空,并且将具有0长度。因为if循环只在条件为真时起作用,并且0是false value-实际上,我们只对非空行进行操作。
代码的最后一部分是另一个if语句。这是一个检查,以确保在从命令提示符执行文件时该文件将运行。在