Sort a CSV file to read in Python Program











up vote
0
down vote

favorite












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









share|improve this question
























  • Can you show us first 5 lines of your csv file?
    – Matina G
    Nov 22 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?
    – user3051029
    Nov 22 at 14:10










  • @MatinaG John 9 Matt 6 test1 0 Mike 3 Hi! 6 I understand this is hard to read as plain text
    – Matt Oram
    Nov 22 at 14:11












  • @user3051029 long story, it's part of the criteria :(
    – Matt Oram
    Nov 22 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.
    – Dan
    Nov 22 at 15:16















up vote
0
down vote

favorite












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









share|improve this question
























  • Can you show us first 5 lines of your csv file?
    – Matina G
    Nov 22 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?
    – user3051029
    Nov 22 at 14:10










  • @MatinaG John 9 Matt 6 test1 0 Mike 3 Hi! 6 I understand this is hard to read as plain text
    – Matt Oram
    Nov 22 at 14:11












  • @user3051029 long story, it's part of the criteria :(
    – Matt Oram
    Nov 22 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.
    – Dan
    Nov 22 at 15:16













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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









share|improve this question















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






python csv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 at 12:02

























asked Nov 22 at 14:05









Matt Oram

54




54












  • Can you show us first 5 lines of your csv file?
    – Matina G
    Nov 22 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?
    – user3051029
    Nov 22 at 14:10










  • @MatinaG John 9 Matt 6 test1 0 Mike 3 Hi! 6 I understand this is hard to read as plain text
    – Matt Oram
    Nov 22 at 14:11












  • @user3051029 long story, it's part of the criteria :(
    – Matt Oram
    Nov 22 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.
    – Dan
    Nov 22 at 15:16


















  • Can you show us first 5 lines of your csv file?
    – Matina G
    Nov 22 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?
    – user3051029
    Nov 22 at 14:10










  • @MatinaG John 9 Matt 6 test1 0 Mike 3 Hi! 6 I understand this is hard to read as plain text
    – Matt Oram
    Nov 22 at 14:11












  • @user3051029 long story, it's part of the criteria :(
    – Matt Oram
    Nov 22 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.
    – Dan
    Nov 22 at 15:16
















Can you show us first 5 lines of your csv file?
– Matina G
Nov 22 at 14:08




Can you show us first 5 lines of your csv file?
– Matina G
Nov 22 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?
– user3051029
Nov 22 at 14:10




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?
– user3051029
Nov 22 at 14:10












@MatinaG John 9 Matt 6 test1 0 Mike 3 Hi! 6 I understand this is hard to read as plain text
– Matt Oram
Nov 22 at 14:11






@MatinaG John 9 Matt 6 test1 0 Mike 3 Hi! 6 I understand this is hard to read as plain text
– Matt Oram
Nov 22 at 14:11














@user3051029 long story, it's part of the criteria :(
– Matt Oram
Nov 22 at 14:13




@user3051029 long story, it's part of the criteria :(
– Matt Oram
Nov 22 at 14:13




1




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.
– Dan
Nov 22 at 15:16




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.
– Dan
Nov 22 at 15:16












2 Answers
2






active

oldest

votes

















up vote
2
down vote













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.






share|improve this answer























  • +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.
    – Risadinha
    Nov 22 at 14:48












  • Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
    – Matt Oram
    Nov 22 at 14:59










  • @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.
    – Lie Ryan
    Nov 22 at 15:11










  • @LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
    – Matt Oram
    Nov 23 at 8:43










  • @LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
    – Matt Oram
    Nov 23 at 9:25




















up vote
1
down vote













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.






share|improve this answer























  • Getting the error 'No module named pandas', do i need to pip install?
    – Matt Oram
    Nov 22 at 14:18






  • 1




    Yes. Note that pandas is a truly usefull module!
    – Matina G
    Nov 22 at 14:18










  • Thanks, I'll let you know how it goes
    – Matt Oram
    Nov 22 at 14:21






  • 2




    If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
    – Idlehands
    Nov 22 at 14:22






  • 1




    My bad, I put a semicolon separator by reflex. Fixed it.
    – Matina G
    Nov 22 at 16:15











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432715%2fsort-a-csv-file-to-read-in-python-program%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote













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.






share|improve this answer























  • +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.
    – Risadinha
    Nov 22 at 14:48












  • Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
    – Matt Oram
    Nov 22 at 14:59










  • @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.
    – Lie Ryan
    Nov 22 at 15:11










  • @LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
    – Matt Oram
    Nov 23 at 8:43










  • @LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
    – Matt Oram
    Nov 23 at 9:25

















up vote
2
down vote













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.






share|improve this answer























  • +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.
    – Risadinha
    Nov 22 at 14:48












  • Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
    – Matt Oram
    Nov 22 at 14:59










  • @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.
    – Lie Ryan
    Nov 22 at 15:11










  • @LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
    – Matt Oram
    Nov 23 at 8:43










  • @LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
    – Matt Oram
    Nov 23 at 9:25















up vote
2
down vote










up vote
2
down vote









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.






share|improve this answer














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.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 22 at 15:22

























answered Nov 22 at 14:38









Lie Ryan

44.2k968121




44.2k968121












  • +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.
    – Risadinha
    Nov 22 at 14:48












  • Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
    – Matt Oram
    Nov 22 at 14:59










  • @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.
    – Lie Ryan
    Nov 22 at 15:11










  • @LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
    – Matt Oram
    Nov 23 at 8:43










  • @LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
    – Matt Oram
    Nov 23 at 9:25




















  • +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.
    – Risadinha
    Nov 22 at 14:48












  • Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
    – Matt Oram
    Nov 22 at 14:59










  • @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.
    – Lie Ryan
    Nov 22 at 15:11










  • @LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
    – Matt Oram
    Nov 23 at 8:43










  • @LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
    – Matt Oram
    Nov 23 at 9:25


















+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.
– Risadinha
Nov 22 at 14:48






+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.
– Risadinha
Nov 22 at 14:48














Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
– Matt Oram
Nov 22 at 14:59




Hi, i got this error message: scores = sorted(reader, key=lambda row: (row[1], row[0])) IndexError: list index out of range
– Matt Oram
Nov 22 at 14:59












@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.
– Lie Ryan
Nov 22 at 15:11




@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.
– Lie Ryan
Nov 22 at 15:11












@LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
– Matt Oram
Nov 23 at 8:43




@LieRyan can't find an error? It is saving to the file just fine, but trips up at the scores = sorted line.
– Matt Oram
Nov 23 at 8:43












@LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
– Matt Oram
Nov 23 at 9:25






@LieRyan update: got it to print the 5 lowest scores...? Edit: Not even the 5 lowest, just 5 random values.
– Matt Oram
Nov 23 at 9:25














up vote
1
down vote













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.






share|improve this answer























  • Getting the error 'No module named pandas', do i need to pip install?
    – Matt Oram
    Nov 22 at 14:18






  • 1




    Yes. Note that pandas is a truly usefull module!
    – Matina G
    Nov 22 at 14:18










  • Thanks, I'll let you know how it goes
    – Matt Oram
    Nov 22 at 14:21






  • 2




    If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
    – Idlehands
    Nov 22 at 14:22






  • 1




    My bad, I put a semicolon separator by reflex. Fixed it.
    – Matina G
    Nov 22 at 16:15















up vote
1
down vote













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.






share|improve this answer























  • Getting the error 'No module named pandas', do i need to pip install?
    – Matt Oram
    Nov 22 at 14:18






  • 1




    Yes. Note that pandas is a truly usefull module!
    – Matina G
    Nov 22 at 14:18










  • Thanks, I'll let you know how it goes
    – Matt Oram
    Nov 22 at 14:21






  • 2




    If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
    – Idlehands
    Nov 22 at 14:22






  • 1




    My bad, I put a semicolon separator by reflex. Fixed it.
    – Matina G
    Nov 22 at 16:15













up vote
1
down vote










up vote
1
down vote









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.






share|improve this answer














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.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 22 at 16:13

























answered Nov 22 at 14:16









Matina G

50619




50619












  • Getting the error 'No module named pandas', do i need to pip install?
    – Matt Oram
    Nov 22 at 14:18






  • 1




    Yes. Note that pandas is a truly usefull module!
    – Matina G
    Nov 22 at 14:18










  • Thanks, I'll let you know how it goes
    – Matt Oram
    Nov 22 at 14:21






  • 2




    If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
    – Idlehands
    Nov 22 at 14:22






  • 1




    My bad, I put a semicolon separator by reflex. Fixed it.
    – Matina G
    Nov 22 at 16:15


















  • Getting the error 'No module named pandas', do i need to pip install?
    – Matt Oram
    Nov 22 at 14:18






  • 1




    Yes. Note that pandas is a truly usefull module!
    – Matina G
    Nov 22 at 14:18










  • Thanks, I'll let you know how it goes
    – Matt Oram
    Nov 22 at 14:21






  • 2




    If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
    – Idlehands
    Nov 22 at 14:22






  • 1




    My bad, I put a semicolon separator by reflex. Fixed it.
    – Matina G
    Nov 22 at 16:15
















Getting the error 'No module named pandas', do i need to pip install?
– Matt Oram
Nov 22 at 14:18




Getting the error 'No module named pandas', do i need to pip install?
– Matt Oram
Nov 22 at 14:18




1




1




Yes. Note that pandas is a truly usefull module!
– Matina G
Nov 22 at 14:18




Yes. Note that pandas is a truly usefull module!
– Matina G
Nov 22 at 14:18












Thanks, I'll let you know how it goes
– Matt Oram
Nov 22 at 14:21




Thanks, I'll let you know how it goes
– Matt Oram
Nov 22 at 14:21




2




2




If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
– Idlehands
Nov 22 at 14:22




If you don't already have pandas, installing it just to sort your csv file is somewhat overkill...
– Idlehands
Nov 22 at 14:22




1




1




My bad, I put a semicolon separator by reflex. Fixed it.
– Matina G
Nov 22 at 16:15




My bad, I put a semicolon separator by reflex. Fixed it.
– Matina G
Nov 22 at 16:15


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432715%2fsort-a-csv-file-to-read-in-python-program%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)