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
if usernames != username2:
是循环的第一次迭代如果输入的名称不在第一行,则表示该名称不在那里,并且在结束程序时从未读取文件的其余部分
你想要
continue
而不是break
下面的代码假设您在第一列中有唯一的名称,这是一个读取整个文件的示例,当您找到该名称时会中断
如果要打印第一列等于输入的所有行,请不要中断循环。。。只需忽略不相等的行,并存储所有匹配行的附加列表
使用Pandas库过滤行也很容易做到这一点
相关问题 更多 >
编程相关推荐