檢查密碼是否在檔案中的程式。檔案來自生成密碼的不同程式。問題是我想檢查檔案中是否有確切的密碼而不是密碼的一部分。密碼都在換行符上。
例如,當密碼 = 'CrGQlkGiYJ95' :如果用戶輸入 'CrGQ' 或 'J95' 或 'k' :輸出為真。我希望它只為確切的密碼輸出 True。
我嘗試了 '==' 而不是 'in' 但即使密碼在檔案中,它也會輸出 False。我還嘗試了 .readline() 和 .readlines() 而不是 .read()。但是對于任何輸入,兩者都輸出錯誤。
FILENAME = 'passwords.txt'
password = input('Enter your own password: ').replace(' ', '')
def check():
with open(FILENAME, 'r') as myfile:
content = myfile.read()
return password in content
ans = check()
if ans:
print(f'Password is recorded - {ans}')
else:
print(f'Password is not recorded - {ans}')
uj5u.com熱心網友回復:
假設您每行有一個密碼,則一種選擇:
def check():
with open(FILENAME, 'r') as myfile:
return any(password == x.strip() for x in myfile.readlines())
如果有匹配,使用生成器可以立即停止。
如果您需要經常重復此操作,最好的方法是構建一個set密碼:
with open(FILENAME, 'r') as myfile:
passwords = set(map(str.strip, myfile.readlines()))
# then every time you need to check
password in passwords
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530149.html
標籤:Python文件
