0

I'm trying to create a leaderboard in python, where a player will get a score from playing a game, which will write to a .csv file. I then need to read from this leaderboard, sorted from largest at the top to smallest at the bottom. Is the sorting something that should be done when the values are written to the file, when i read the file, or somewhere in between?

my code:

writefile=open("leaderboard.csv","a")
writefile.write(name+", "points)
writefile.close()

readfile=open("leaderboard.csv","r")

I'm hoping to display the top 5 scores and the accompanying names. It is this point that I have hit a brick wall. Thanks for any help.

Edit: getting the error 'list index out of range'

import csv

name = 'Test'
score = 3

with open('scores.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerow([name, score])

with open('scores.csv') as f:
    reader = csv.reader(f)
    scores = sorted(reader, key=lambda row: (float(row[1]), row[0]))
    top5 = scores[-5:]

csv file:

test1   3

test2   3

test3   3
9
  • Can you show us first 5 lines of your csv file? Commented Nov 22, 2018 at 14:08
  • Why don't you just serialize the scoreboard with pickle? What's the point of .csv file, if you both write/read in python code? Commented Nov 22, 2018 at 14:10
  • @MatinaG John 9 Matt 6 test1 0 Mike 3 Hi! 6 I understand this is hard to read as plain text Commented Nov 22, 2018 at 14:11
  • @user3051029 long story, it's part of the criteria :( Commented Nov 22, 2018 at 14:13
  • 1
    name+", "points is not going to work as you hope if name has comma characters in it. You'll want to wrap those in quotation marks or something like that. Better to use the csv module or pandas as in the answers below which will handle all of that for you. Commented Nov 22, 2018 at 15:16

2 Answers 2

2

Python has a csv module in the standard library. It's very simple to use:

import csv

with open('scores.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerow([name, score])

with open('scores.csv') as f:
    reader = csv.reader(f)
    scores = sorted(reader, key=lambda row: (float(row[1]), row[0]))
    top5 = scores[-5:]

Is the sorting something that should be done when the values are written to the file, when i read the file, or somewhere in between?

Both approaches have their benefits. If you sort when you read, you can simply append to the file, which makes writing new scores faster. You do take more time when reading as you have to sort it before you can figure out the highest score, but in a local leaderboard file this is unlikely to be a problem as you are unlikely to have more than a few thousands of lines, so you'll likely be fine with sorting when reading.

If you sort while writing, this comes with the problem that you'll have to rewrite the entire file every time a new score is added. However, it's also easier to cleanup the leaderboard file if you sort while writing. You can simply remove old/low scores that you don't care about anymore while writing.

Sign up to request clarification or add additional context in comments.

18 Comments

+2 because for using the csv module. CSV does not mean to just join your values with the separator without caring for escapes, line breaks or whatever comes along. If the file is larger than a few lines and you plan to have more files lying around, wrap that easily with the gzip module and you'll save a lot of disk space.
Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
@MattOram: your input file contains an error most likely, or it may have used a different csv dialect (the csv module can be configured for different dialects). If you used my code to both write and read the CSV though, you shouldn't havea problem . Also, note there's a little unrelated errata on that line as the score should be sorted as numeric value instead of as a string.
@LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
@LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
|
1

Try this:

import pandas as pd
df = pd.read_csv('myfullfilepath.csv', sep=',', names=['name', 'score'])
df = df.sort_values(['score'], ascending=False)
first_ten = df.head(10)
first_ten.to_csv('myfullpath.csv', index=False). 

I named the columns like that , following the structure tat you suggested.

8 Comments

Getting the error 'No module named pandas', do i need to pip install?
Yes. Note that pandas is a truly usefull module!
Thanks, I'll let you know how it goes
If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
My bad, I put a semicolon separator by reflex. Fixed it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.