我一直在尝试从csv文件中获得前5名的记分牌,但我一直在努力。
这是我的代码,如果有人可以帮助您,将不胜感激
while True:
if attempt == 2:
print("You have no more guesses...You Loose!")
print("Here is the scoreboard")
user = str(input("Enter a name to save your highscore: "))
file = open ("scoreboard.csv", "a")
file.write("\n")
file.write(user)
file.write(",")
file.write(str(points))
file.write("pts")
file.write("\n")
答案 0 :(得分:0)
您可以尝试使用此功能。 除非您希望它们之间有换行符,否则您无需在开头和结尾处换行。 您还希望使用“打开时”自动关闭文件。
while True:
if attempt == 2:
print("You have no more guesses...You Loose!")
print("Here is the scoreboard")
user = str(input("Enter a name to save your highscore: "))
with open("scoreboard.csv", "a") as output:
output.write("\n"+user+","+str(points)+" pts")
答案 1 :(得分:0)
CSV模块非常方便。
user
和points
紧随您的输入。
使用的是Python 3.6 +。
import csv
with open('scoreboard.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow([user, f"{points}pts"])
scoreboard.csv
例如:user =“ john”,点数= 10
john,10pts
答案 2 :(得分:0)
csv为:
david,12
bill,8
joe,18
henry,15
nathan,10
您可以使用此功能:
import csv
def top_five():
top = []
all_scores = []
with open('scores.csv', newline='') as csvfile:
scores = csv.reader(csvfile)
for row in scores:
all_scores.append((row[0], int(row[1])))
top = sorted(
all_scores,
key=lambda score: score[1],
reverse=True)
return top[:5]
print(top_five())
如果您将“ pts”保留在csv中,请在all_score列表中插入之前解析结果。 如果您有列名,请跳过for循环的第一行。