2017-05-17 34 views
0

TL檢查爲正確的; DR - 閱讀題,該死Python中無法識別輸入時對另一個變量

我是相當新的蟒蛇 - 更具體地說,文件處理的蟒蛇 - 和我工作的事爲了學校;我試圖在python中簡單地登錄系統(沒有任何安全或任何東西,只是一個基本框架)。我想知道有關這方面的最佳方法。我想過的方法是在一個設置目錄中有一個設置文件夾,其中包含所有根據它們存儲的密碼的用戶名命名的文件(例如,「jacksonJ.txt」將保存該用戶的密碼)。然後用戶輸入他們的用戶名,python獲取該文件,讀取密碼,然後檢查用戶輸入的密碼與實際密碼。我的問題是;即使輸入了正確的密碼,python似乎也無法識別該密碼。

from pathlib import Path 
usr=input("Username: ") 

#creating a filepath to that user's password document 
filepath=("C:\\python_usr_database\\"+usr+".txt") 

#make sure that file actually exists 
check= Path(filepath) 

#if it does, let them enter their password, etc 
if check.is_file(): 

    #open their password file as a variable 
    with open (filepath, "r") as password: 
     pass_attempt=input("Password: ") 

     #check the two match 
     if pass_attempt==password: 
      print("Welcome back, sir!") 
     else: 
      print("BACK OFF YOU HACKER") 

#if it isn't an existing file, ask if they want to create that user 
else: 
    print("That user doesn't seem to exist yet.") 
    decision=input("Would you like to create an account? y/n ").lower() 
    # do some stuff here, this part isn't all too important yet 
+1

'password'是文件,而不是它的內容。你需要'.read()'文件來獲得它的內容 – asongtoruin

+0

謝謝!就像我說的,我對此很新... –

回答

0

你需要,當你打開它來獲取它的內容讀取文件 - 你的問題是,你是比較對文件的字符串。請嘗試以下操作:

from pathlib import Path 
usr=input("Username: ") 

#creating a filepath to that user's password document 
filepath=("C:\\python_usr_database\\"+usr+".txt") 

#make sure that file actually exists 
check= Path(filepath) 

#if it does, let them enter their password, etc 
if check.is_file(): 
    #open their password file as a variable 
    with open (filepath, "r") as f: 
     password = f.read() 
    pass_attempt=raw_input("Password: ") 

    #check the two match 
    if pass_attempt==password: 
     print("Welcome back, sir!") 
    else: 
     print("BACK OFF YOU HACKER") 
#if it isn't an existing file, ask if they want to create that user 
else: 
    print("That user doesn't seem to exist yet.") 
    decision=input("Would you like to create an account? y/n ").lower() 
    # do some stuff here, this part isn't all too important yet 
1

要獲取文件的內容,您需要執行file.read()。這將返回一個內容的字符串。 所以:

with open(filepath, "r") as password_file: 
    password = password_file.read() 
password_attempt = input("password: ") 
# Compare, then do stuff... 
+0

謝謝!這工作 –