2017-10-08 9 views
1

私はクイズプログラムのログインシステムを作成しようとしていますが、私が望む結果を得ることができません。最初の関数は、ユーザーのためにファイルを作成します。後でそれらのファイルの詳細を保存することができますが、これは私が苦労している部分ではなく、参考のためだけにあります。私が働くことができないビットは、ユーザーファイルの1行目が入力された文字列(パスワード)と等しい場合、2番目の関数にあります。なぜなら、プログラムと同じではないことを常に教えているからですパスワードが一致しないため、ユーザーが作成したファイルにデータを保存することはできません。どうすればこの問題を解決できるか教えてください。Pythonで再利用可能なログインを作成できません

def create_login(): 
YorN = "nothing" 
while YorN != "y": 
    name = raw_input(str("please input full name:")) 
    age = raw_input(str("please input age:")) 
    username = name[0:3] + age 
    password = raw_input(str("please enter password:")) 
    print "Are you sure you want to proceed with the username and password you have selected?" 
    YorN = (raw_input("Please select Y or N:")).lower() 
f = open(username +".txt","w+") 
f.write(password) 
f.write("\n") 
f.write(name) 
f.write("\n") 
f.write(age) 
f.write("\n") 
f.write(username) 
f.write("\n") 
f.close() 

def login(): 
    inp_username = raw_input(str("Please input your username:")) 
    inp_password = raw_input(str("Please input your password:")) 
    t = open(inp_username +".txt","r") 
    lines = t.readlines() 
    g = lines[0] 
    if inp_password == g: 
     print "Access Granted!" 
    else: 
     print "incorrect password" 
     login_or_create() 
+0

'.readlines()'は、改行文字のついた文字列を返します。ユーザーの入力と比較する前に、それを除去する必要があります。 – jasonharper

答えて

0

問題:

テキストファイルの各行はnewline文字で終わります。 1行または複数の行を読み込むと、それぞれにはその改行文字が添付されています。

しかし、改行文字で終わっていない、あなたのパスワードが一致しません:

password => 'mypassword' 
line_read_in_from_file => 'mypassword\n' 

ソリューション:以前に関連付けられている.strip()機能を使用して、比較を行うことに改行文字オフ

strip() Pythonの文字列...

def login(): 
    inp_username = raw_input(str("Please input your username:")) 
    inp_password = raw_input(str("Please input your password:")) 
    t = open(inp_username +".txt","r") 
    lines = t.readlines() 

    # lines[0] is a string and as a string, has a function called .strip() 

    g = lines[0].strip() 
    if inp_password == g: 
     print "Access Granted!" 
    else: 
     print "incorrect password" 
     login_or_create() 
0

[0]行から\ nを取り除いて、あなたのユーザー名を教えてくださいsersすなわちname [0:3] + ageはユーザ名です。

関連する問題