阅读整个文档并在python中匹配一个部分

时间:2014-01-11 19:14:58

标签: python

我的问题是,我如何比较一个完整文档中的用户名和密码,以确定它是否在那里。到目前为止我有这个:

regorlog = raw_input("press 1 to register, press 2 to log in! \n")

if regorlog == "1":
    uname = raw_input("what is your desired username?\n")
    pwd = raw_input("what is your desired password?\n")
    pwd2 = raw_input("please retype your password\n")
    if (pwd == pwd2):
        file = open("userlog.txt", "a")
        file.write(uname + " || " + pwd + "\n")
        file.close()
    else:
        print 'sorry, those passwords do not match'
elif regorlog == "2":
    loguname = raw_input("what is your username? \n")
    logpwd = raw_input("what is your password? \n")
    file = open("userlog.txt", "r")
        #here, I need to read the file userlog.txt, and look and see if the username and password combination exists in the file somewhere.
        file.close()

我无法阅读整个文件,并且正在寻找用户名和密码组合。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

我建议使用内置模块为您执行此操作:

import shelve

regorlog = raw_input("press 1 to register, press 2 to log in! \n")

if regorlog == "1":
    uname = raw_input("what is your desired username?\n")
    pwd = raw_input("what is your desired password?\n")
    pwd2 = raw_input("please retype your password\n")
    if pwd == pwd2:
        shelf = shelve.open("userlog.txt", "c")
        shelf[uname] = pwd
        shelf.close()
    else:
        print 'sorry, those passwords do not match'
elif regorlog == "2":
    loguname = raw_input("what is your username? \n")
    logpwd = raw_input("what is your password? \n")

    shelf = shelve.open("userlog.txt", "c")
    try:
        matched = shelf[loguname] == logpwd
    except KeyError:
        matched = False
    shelf.close()

    print 'Matched: ', matched

编辑:修复。我建议更改文件的名称,但

答案 1 :(得分:0)

我只是想通了。这就是我最终做的事情!

regorlog = raw_input("press 1 to register, press 2 to log in! \n")

if regorlog == "1":
    uname = raw_input("what is your desired username?\n")
    pwd = raw_input("what is your desired password?\n")
    pwd2 = raw_input("please retype your password\n")
    if (pwd == pwd2):
        file = open("userlog.txt", "a")
        file.write(uname + " || " + pwd + "\n")
        file.close()
    else:
        print 'sorry, those passwords do not match'
elif regorlog == "2":
    loguname = raw_input("what is your username? \n")
    logpwd = raw_input("what is your password? \n")
    file = open("userlog.txt", "r")
    if loguname + " || " + logpwd in open('userlog.txt').read():
        print "true"
    file.close()

答案 2 :(得分:0)

改变你所拥有的最后一部分:

# ...
elif regorlog == "2":
    loguname = raw_input("what is your username? \n")
    logpwd = raw_input("what is your password? \n")

    login_info = loguname + " || " + logpwd
    with open("userlog.txt", "r") as users_file: # closes the file automatically
        if any(login_info == line.rstrip() for line in users_file):
            # if any line in the file matches
            print "true"

但是为了安全的爱,请不要将密码存储为明文

https://crackstation.net/hashing-security.htm