从文件中读取行对

时间:2014-03-18 15:19:56

标签: python python-2.7 csv

我希望它读取0行和0行,0表示用户名,1表示密码,如果找不到,则在行号中加2,所以读取2表示用户名,然后3表示密码和等等。

我的文件如下:

daniel
password
user
password
user
password
etc user
etc password

def PupilLogin():

    print "*********************************"
    print "* Welcome to Spelling Bee Pupil *"
    print "*********************************"
    print "Enter your details below..\n"
    strID = raw_input("Username : ")
    strPassWd = getpass.getpass("Password : ")
    with open('studentsusers.csv', 'rb') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        username = 0
        password = 1
        for row in spamreader:
            strLoginID = row[username]
            strLoginPasswd = row[password]
            while strLoginID != "":
                if strID == strLoginID and strLoginPasswd == strPassWd:
                    print strID, "Logged In"
                    PupilMenu()
                    strContinue = sys.stdin.readline()
                    return
                else:
                    username += 2
                    password += 2
    #if we get here there is no such login and id
    print "Login ID or password incorrect, press enter to continue"
    strContinue = sys.stdin

我认为问题与我没有使用整数的事实有关但我实际上没有线索我认为我在这里是愚蠢的,说实话只是希望得到任何帮助。

2 个答案:

答案 0 :(得分:1)

我认为问题是你的代码需要一个逗号分隔的csv文件,它看起来像这样:

daniel, password
user, password

因此每行都有一个用户名(row[0])和一个密码(row[1]),用逗号分隔。您可以使用username, password = row形式轻松地将这些变量分配给变量。

代码的for row in spamreader部分遍历每一行,因此在第一次迭代时,row等于["daniel", "password"]等。

我会更改您的.csv文件以适合该格式,然后执行代码的相关部分:

strID = raw_input("Username : ")
strPassWd = getpass.getpass("Password : ")

with open('studentsusers.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')

    for row in spamreader:
        strLoginID, strLoginPasswd = row

        while strLoginID != "":
            if strID == strLoginID and strLoginPasswd == strPassWd:
                print strID, "Logged In"
                PupilMenu()
                strContinue = sys.stdin.readline()
                return
            else:
                break   # goes on to the next row in spamreader

#if we get here there is no such login and id
print "Login ID or password incorrect, press enter to continue"
strContinue = sys.stdin

编辑:我应该提一下,一旦你不再需要文件资源,通常是个好主意。在这个例子中,一旦用户登录就不再需要你的csv文件,所以我会考虑拔出PupilMenu()调用并在文件关闭后调用(即with阻止)。考虑一下:

strID = raw_input("Username : ")
strPassWd = getpass.getpass("Password : ")

loggedIn = False

with open('studentsusers.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')

    for row in spamreader:
        strLoginID, strLoginPasswd = row

        while strLoginID != "":
            if strID == strLoginID and strLoginPasswd == strPassWd:
                print strID, "Logged In"
                loggedIn = True
                return
            else:
                break   # goes on to the next row in spamreader

if loggedIn:
    PupilMenu()
    strContinue = sys.stdin.readline()
else:
    print "Login ID or password incorrect, press enter to continue"
    strContinue = sys.stdin
编辑2:我重新编写了一些代码,只是为了好玩。我认为这更容易阅读/理解:

def Welcome():
    print "*********************************"
    print "* Welcome to Spelling Bee Pupil *"
    print "*********************************"
    print "Enter your details below..\n"

    strID = raw_input("Username : ")
    strPassWd = getpass.getpass("Password : ")

    if loggedIn(strID, strPassWd):
        PupilMenu()
        strContinue = sys.stdin.readline()
    else:
        print "Login ID or password incorrect, press enter to continue"
        strContinue = sys.stdin

def loggedIn(user, password)
    with open('studentsusers.csv', 'rb') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')

        for row in spamreader:
            strLoginID, strLoginPasswd = row

            while strLoginID != "":
                if strLoginID == user and strLoginPassWd == password:
                    print user, "Logged In"
                    return True
                else:
                    break

答案 1 :(得分:0)

如果您需要将用户名和密码存储在不同的行中,您可以这样做。

所以,关于python文件输入对象的一个​​简洁的事情就是你可以自动遍历这些行!所以你甚至不需要你的csv读者:

with open('inputfile', 'r') as inputfile:
   for line in inputfile:
       print line

这将打印文件的每一行。

然后,为了读取成对的行,我们可以使用一个很酷的python技巧将列表转换为成对列表。

with open('passwords_file', 'r') as f:
  from itertools import izip
  line_iter = iter(f)
  for username_line, password_line in izip(line_iter, line_iter):
     if strID == username_line.rstrip() and strPassWd == password_line.rstrip():
        print strID, "Logged In"
        PupilMenu()
        strContinue = sys.stdin.readline()
        return
  # If you make it here, the username/password pair wasn't found.

rstrip()是必要的,因为否则结尾将成为字符串的一部分。)

最后,每次用户输入密码时,您可能都不希望线性浏览数据库。最好先将用户名/密码组合读入字典,然后使用该字典进行登录!这样,您可以让用户一遍又一遍地尝试,直到他们得到它,更有效率。

import getpass

def AttemptLogIn(user_to_passwd):
   while True:
     strID = raw_input("Username : ")
     strPassWd = getpass.getpass("Password : ")

     if strID not in user_to_passwd or user_to_passwd[strID] != strPassWd:
        print "Sorry, username or password not found."
     else:
        print strID, "Logged In"
        return

user_to_passwd = {}

with open('passwords_file', 'r') as f:
  line_iter = iter(f)
  from itertools import izip
  for username, password in izip(line_iter, line_iter):
    user_to_passwd[username.rstrip()] = password.rstrip()

AttemptLogIn(user_to_passwd)

PupilMenu()
strContinue = sys.stdin.readline()