Pthyon
Pthyon

Reputation: 172

Sorting CSV file based on scores

I cannot figure out how to print and sort my csv file which involves the scores, names, and times of players in my game so I can print the top 5 scores.

Iv been looking through stackoverflow for a while and cannot find anything which matches to the specifications I require or fits what I need. So if someone could help that would be awesome.

My csv file looks as follows:

Human,02:00,120
Joe,03:00,180
Alex,01:00,60
Jason,05:00,300
Liza,06:00,360
John,07:00,420
Mark,04:00,240

The file columns are: Name, Time, RawTime. The RawTime column is what I would want to sort in order to list the lowest to highest times within the top 5

def addtoScoreboard(name, time, scores):
    file = open("scores.csv", "a")
    file.write("\n" + str(name) + "," + str(time) + "," + str(scores))
    file.close

This is how I'm adding my scores to the text file.

It would be really cool if someone could aid me in order to sort and print the data within my csv file which I can later add to my game.

Upvotes: 0

Views: 146

Answers (5)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

This should do it.

import csv

li = []
#Import the csv as a dictionary
with open("out.csv") as infile:
    reader = csv.DictReader(infile)

    #Append all items to a list
    for item in reader:
        li.append(dict(item))

#Sort the list on Rawtime key
res = sorted(li, key=lambda x:int(x['RawTime']), reverse=True)

#Remove Rawtime from result
res = [ {i:item[i] for i in item if i!='RawTime'} for item in res[:5]]
print(res)

#Print without Name and List
for item in res:
    print(','.join(list(item.values())))

#Write to a csv
keys = ['Name', 'Time']
with open('out.csv', 'w') as outfile:

    writer = csv.DictWriter(outfile, keys)
    #Write the header
    writer.writeheader()
    #Write the keys
    for item in res:
        writer.writerow(item)

So if the csv looks like

Name,Time,RawTime
Human,02:00,120
Joe,03:00,180
Alex,01:00,60
Jason,05:00,300
Liza,06:00,360
John,07:00,420
Mark,04:00,240

The output will be

[{'Name': 'John', 'Time': '07:00'}, 
{'Name': 'Liza', 'Time': '06:00'}, 
{'Name': 'Jason', 'Time': '05:00'}, 
{'Name': 'Mark', 'Time': '04:00'}, 
{'Name': 'Joe', 'Time': '03:00'}]

And the output csv will look like

Name,Time
John,07:00
Liza,06:00
Jason,05:00
Mark,04:00
Joe,03:00

Printing without name and list looks like

John,07:00
Liza,06:00
Jason,05:00
Mark,04:00
Joe,03:00

Upvotes: 1

araraonline
araraonline

Reputation: 1562

There is also the pandas library, that, although being a bit overkill, allows you to write more concise code:

import pandas as pd

df = pd.read_csv('input.csv', names=["Name", "Time", "RawTime"])
df = df.sort_values('RawTime')
df.to_csv('scores.csv', header=False, index=False)

Upvotes: 1

Akhilesh_IN
Akhilesh_IN

Reputation: 1307

you can use pandas for same

import pandas as pd
df = pd.read_csv('input_file.csv',header=None)

(df.sort_values([2],ascending=False) ## sorting high to low on column 2
 .head(5) ## taking top 5
 .sort_values([2],ascending=True) ## sorting low to high
 .to_csv('scores.csv',header = False,index=False)) # exporting as csv

Upvotes: 0

Rakesh
Rakesh

Reputation: 82755

Using the csv module. And using sorted() with key to sort by time.

Ex:

import csv

with open(filename, "rU") as infile:
    reader = csv.reader(infile)
    data = [row for row in reader]
    data = sorted(data, key=lambda x: int(x[-1]))   #Sort by RawTime

with open(filename_1, "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerows(data)

Output:

Alex,01:00,60
Human,02:00,120
Joe,03:00,180
Mark,04:00,240
Jason,05:00,300
Liza,06:00,360
John,07:00,420

Upvotes: 1

pzk
pzk

Reputation: 19

data_arr = []
with open("your_file.txt") as f:
    for line in f.readlines():
        name, time, raw_time = line.split(",")
        data_arr.append((name, time, int(raw_time)))

    data_arr = sorted(data_arr, key= lambda x: x[2])

with open("output_file.txt", "w") as f:
    output = ""
    for name, time, raw_time in data_arr:
        output += (name + "," + time + "," + str(raw_time)) + "\n"
    f.write(output)

Upvotes: 0

Related Questions