2017-05-17 29 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

谢谢!这工作 –