开发者

Sorting and aligning the contents of a text file in Python

开发者 https://www.devze.com 2022-12-24 16:10 出处:网络
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:

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 sco开发者_如何学JAVAre
    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


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


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)


  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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号