2017-05-17 6 views
0

TLに対してチェックするときのように正しい入力を認識しない; - 、タイトルを読んでPythonは別の変数

が私のpythonにかなり新しいよくそ - DRより具体的に、ファイルはPythonでの取り扱い - と私は何かに取り組んでいます学校のために;私はPythonだけでシンプルなログインシステム(セキュリティや何もない、基本フレームのみ)を作ろうとしています。私はこれについて最善の方法を考えていた。私が思った方法は、set directoryにset folderを置くことです。そこには、保存したパスワードのユーザ名に基づいて名前が付けられたファイルが含まれています(例えば、 "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を行う必要があり、ファイルの内容を取得するには()。これは、コンテンツの文字列を返します。 So:

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

ありがとう!これは働いた –

関連する問題