2016-04-28 65 views
0

我想做一个银行,其中存储用户输入的用户名和密码在一个文件(文本文件)。现在,当用户登录时,他输入他的用户名。现在如何比较是否输入此用户名当他/她创建账户(存储在passw.txt中)时,用户与存储的密码相同。
这里是我的代码,如何将用户输入的用户名与存储在文件中的密码进行比较?

store_user=open("user.txt","a") 
store_passw=open("passw.txt","a") 
print "Type 1 to create a new acc or 2 to log in" 
a=input("Your choice: ") 
if a==1: 

    a=raw_input("Enter your username: ") 
    store_user.write(a+'\n') 
    store_user.close() 

    b=raw_input("Enter pass: ") 
    store_passw.write(b+'\n') 
    store_passw.close() 
elif a==2: 
    a=raw_input("Enter username: ") 
    ''' 

    Now how do I comapare the username entered by the user with my file user.txt 
    And also it should check the same userame has same associated password with passw.txt 

    '''  

我也想知道的是,这种方法更容易或应我存储的用户名和密码字典,然后在文件。如果它追我这样做,那会怎样我从中得到用户名和密码? (就像用户输入他的用户名,现在我的程序如何进入存储用户名和密码的文件,并检查用户名(密钥)是否与密码(值)匹配。

回答

0

您需要一个结构。你可以使用行号来获得pair - user-password,这会带来更多的问题,然后你可以期待,请使用结构,保持数据的一致性,例如你可以把它们放入单个文件 - 读取整个记录 - 名称,密码 - 简单的方法 - 像逗号分隔值 - python有csv模块 - https://docs.python.org/2/library/csv.html或者你可以去更复杂的东西 - JSON,XML - 这里是链接json:https://docs.python.org/2/library/json.html

0

我个人不会存储在2个文件中,而是使用两个文件之间的分隔符元素和其他分隔符值之间该元素

例“的Test1,PASS1 \ nTest2,PASS2”将是分隔符“\ n”和“”

为您的代码,你将不得不找到linecount在文件1然后跳到另一个文件中该行比较密码:

psudocode

open username 
linefound = -1 
for line,lineid in file 
    if line == user 
     linefound = lineid 
close username 
if linefound >= 0 
    open password 
    for line, lineid in file 
     if lineid == linefound 
      //compare do rest 
相关问题