tags:

views:

143

answers:

3

In my program I have a text file that I read from and write to. However, I would like to display the contents of the text file in an aligned and sorted manner. The contents currently read:

Emily, 6
Sarah, 4
Jess, 7

This is my code where the text file in read and printed:

elif userCommand == 'V':
    print "High Scores:"
    scoresFile = open("scores1.txt", 'r')
    scores = scoresFile.read().split("\n")
    for score in scores:
        print score
    scoresFile.close()

Would I have to convert this information into lists in order to be able to do this? If so, how do I go about doing this?

When writing to the file, I have added a '\n' character to the end, as each record should be printed on a new line.

Thank you

+5  A: 

You could use csv module, and then could use sorted to sort.

Let's says, scores1.txt have following

Richard,100
Michael,200
Ricky,150
Chaung,100

Test

import csv

reader=csv.reader(open("scores1.txt"),dialect='excel')
items=sorted(reader)
for x in items:
    print x[0],x[1]

...
Emily  6
Jess  7
Sarah  4
S.Mark
I have added my code above where the contents of the text file is read and printed. Would you be able to give me more information on how to use the csv module and what it does?
Emily Price
@Emily, added some test codes, let me know if you still have some problems
S.Mark
I am still having problems, I'm sorry. I couldn't get this to work. Each record has to be printed on a new line aswell.
Emily Price
@Emily, what does your scores1.txt looks like? could you post some part of it?
S.Mark
Added some additional information above
Emily Price
@Emily, to print that, you just need to loop it
S.Mark
Does it all go inside a for loop? And just to increase my understanding, what does the dialect='excel' section do?
Emily Price
Its meant for Excel-Generated CSV file, the very basic of CSV format.
S.Mark
A: 
  1. to sort stuff in Python, you can use sort()/sorted().
  2. to print, you can use print with format specifiers, str.rjust/str.ljust, pprint etc
ghostdog74
+2  A: 

Looks like nobody's answered the "aligned" part of your request. Also, it's not clear whether you want the results sorted alphabetically by name, or rather by score. In the first case, alphabetical order (assuming Python 2.6):

with open("scores1.txt", 'r') as scoresFile:
  names_scores = [[x.strip() for x in l.split(',', 1)] for l in scoresFile]
# compute column widths
name_width = max(len(name) for name, score in names_scores)
score_width = max(len(score) for name, score in names_scores)
# sort and print
names_scores.sort()
for name, score in names_scores:
  print "%*s %*s" % (name_width, name, score_width, score)

If you want descending order by score, just change the names_scores.sort() line to two:

def getscore_int(name_score): return int(name_score[1])
names_scores.sort(key=getscore_int, reverse=True)
Alex Martelli
@Alex, maybe there is a typo? the line starts with "name_width = " and the line starts with "score_width = " should ends with a ")", not a "]"
sunqiang
@sunqiang -- you're right, tx for spotting this. Editing to fix.
Alex Martelli
what about ascending order by score?
Emily Price
Is it possible to get ascending order without defining functions?
Emily Price
@Emily, ascending vs descending depends only on whether you add `reverse=True` to the call or not. Extracting the score **as an `int`** for sorting purposes (so that 2 sorts before 11, etc) does require a function, though you can leave it unnamed (with a `lambda`) if you insist (makes your code less clear). Or, you can instead use a loop of `namescore[1]=int(namescore[1])` then `operator.itemgetter` (also a lot less clear IMNSHO).
Alex Martelli