我在文本文件中搜索密码,但是它说每次都找不到密码,尽管密码存在于文件中。
这是我目前的代码:
import pickle
import time
print "Do you already have a database created"
y=raw_input("'yes' to continue")
if y=='yes': #to search password in text file
infile=open(r"C:\Users\pc\Desktop\itika study material\cs\password.txt", "r")
Passwords = infile.readlines()
while True:
InputPassword = raw_input("Enter your password.")
print "Searching for password."
time.sleep(2)
if InputPassword in Passwords:
print "your password has been found, you can access your database"
break
else:
print "your password has Not been found." #only prints this statement
break
答案 0 :(得分:0)
可能是您的Passwords
变量包含换行符而您的InputPassword
数组不包含换行符。尝试使用非常简单的设置在调试器中查看它们以确认存在完全匹配。请记住,in
函数必须完全匹配才能正常工作。
答案 1 :(得分:0)
尝试使用Passwords = infile.read()
代替Passwords = infile.readlines()
。这将读取整个文件,并允许您搜索整个文件中的InputPassword
字符串。
请注意,这不是对密码的安全检查。
答案 2 :(得分:0)
在“ Passwords”变量中创建的列表中包含“ \ n”。 只需去除\ n,它应该可以正常工作
这是正确的:
import pickle
import time
print("Do you already have a database created")
y = input("'yes' to continue")
if y == 'yes': # to search password in text file
Passwords = list(
map(lambda x: x.strip(), (open(r"password.txt", "r")).readlines()))
# Passwords = "infile"
print(type(Passwords))
print(Passwords)
while True:
InputPassword = input("Enter your password.")
print("Searching for password: ", end=" ")
print(InputPassword)
time.sleep(2)
if InputPassword in Passwords:
print("your password has been found, you can access your database")
break
else:
print("your password has Not been found.")
break