如何打印与用户名关联的多个变量?

时间:2017-11-05 13:58:46

标签: python python-3.x csv

def usernameresults():
    username2 = input("Please input the username you want to explore: ")
    leaderboardfile = open("leaderboard.txt","r")
    lbfrec = leaderboardfile.readline()
    while lbfrec != "":
        field = lbfrec.split(",")
        usernames = field[0]
        topic = field[1]
        difficult = field[2]
        scores = field[3]
        percentages = field[4]
        grades = field[5]
        if usernames != username2:
            print("Error, username not found")
            break
        else:
            print("These are the search results:\nUsername is ",usernames, "\nTopic is ",topic,
              "\nDifficulty is ",difficult, "\nNumber of questions correct are ",scores,
              "\nThe percentage is",percentages, "\nThe grade is ",grades)
            lbfrec = leaderboardfile.readline()
    leaderboardfile.close()

上面的代码应打印出与输入的用户名相关的所有信息,但是,它只打印一批信息,即使文件中有与该用户名相关的多个变量,我如何获得程序打印出与用户名相关的所有信息,而不仅仅是一行?

in the file (leaderboard.txt) = 
 aad15,maths,Easy,3,100,A  <-- only prints this
 aad15,history,Easy,3,100,A  <-- but not this (i want it to print both)
 mas15,history,Hard,5,100,A

1 个答案:

答案 0 :(得分:0)

if usernames != username2:正在循环的第一次迭代中发生。

如果您输入的名称不在第一行,则表示该名称不在那里,并且您在没有阅读其余内容的情况下结束该程序文件。

您希望continue代替break

以下代码假定您在第一列中有唯一的名称,它是读取整个文件的示例,并在您找到名称时中断

def usernameresults():
    username2 = input("Please input the username you want to explore: ")
    found_userline = None
    with open("leaderboard.txt") as leaderboardfile:
        for line in leaderboardfile:

            field = line.split(",")
            username = field[0]

            if username == username2:
                print("username found")
                found_userline = line 
                break

    if found_userline is not None:
        topic, difficult, scores, percentages, grades = found_userline.split(',')[1:]
        print("These are the search results:\nUsername is ",usernames, "\nTopic is ",topic,
          "\nDifficulty is ",difficult, "\nNumber of questions correct are ",scores,
          "\nThe percentage is",percentages, "\nThe grade is ",grades)
    else:
        print("{} not found".format(username2)) 

如果您要打印所有行,其中第一列等于您的输入,那么请不要中断循环...只需忽略不相等的行,并存储一个额外的行所有匹配行的列表

使用Pandas库过滤行

也很容易