为了简化代码,我做了一些修改而不影响结果。def login():
username = "test"
password = "test"
database=open('database.txt')
for line in database.readlines():
usr, pas = line.strip().split("-")
if (username in usr) and (password in pas):
print ("welcome")
return True
print ("error")
return False
login()
为了检查读取线方法的完全结果,我打印了从文件中读取的列表。def login():
username = "test"
password = "test"
database=open('database.txt')
print (database.readlines())
for line in database.readlines():
print (line)
usr, pas = line.strip().split("-")
print (usr,pas)
if (username in usr) and (password in pas):
print ("welcome")
return True
print ("error")
return False
login()
输出:['abc-123 \n', 'test-test \n', 'user-pass']
因此bug不是由于database.readlines()不起作用,而是因为打印后的代码(database.readlines())。
而database.readlines()成为[]!
这是因为在我们第一次分配readlines方法后,文件光标指向文件的末尾。因此,除非将文件光标更改为文件的开头,否则我们无法再读取任何字符。
而你的问题是每次if-case句子结束后返回!修改返回假句的缩进后,如果没有用户名和密码可以匹配,将分配该问题,问题将得到解决!
现在我们只修改代码:def login():
username = "test"
password = "test"
database=open('database.txt')
print (database.readlines())
print (database.readlines())
for line in database.readlines():
print (line)
usr, pas = line.strip().split("-")
print (usr,pas)
if (username in usr) and (password in pas):
print ("welcome")
return True
print ("error")
return False
login()