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

2024-05-29 08:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: theto信息fieldinputisusername用户名
1条回答
网友
1楼 · 发布于 2024-05-29 08:29:33

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库过滤行也很容易做到这一点

相关问题 更多 >

    热门问题