在Python中排序和对齐文本文件内容
在我的程序中,我有一个文本文件,可以从中读取内容,也可以写入内容。不过,我想把这个文本文件的内容以对齐和排序的方式展示出来。目前读取的内容是:
Emily, 6
Sarah, 4
Jess, 7
这是我读取文本文件并打印内容的代码:
elif userCommand == 'V':
print "High Scores:"
scoresFile = open("scores1.txt", 'r')
scores = scoresFile.read().split("\n")
for score in scores:
print score
scoresFile.close()
我需要把这些信息转换成列表才能做到这一点吗?如果是的话,我该怎么做呢?
在写入文件时,我在每条记录的末尾加了一个'\n'字符,因为每条记录应该在新的一行打印。
谢谢
3 个回答
0
- 在Python中,要对东西进行排序,你可以使用 sort() 或 sorted()。
- 如果你想打印内容,可以使用带格式的打印方法,比如 print,或者用 str.rjust/str.ljust,甚至 pprint 等等。
2
看起来没有人回答你提到的“对齐”部分。另外,你想要的结果是按名字的字母顺序排序,还是按分数排序,这一点也不太清楚。如果你想按字母顺序排序(假设使用的是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)
如果你想按分数从高到低排序,只需要把names_scores.sort()
这一行改成两行:
def getscore_int(name_score): return int(name_score[1])
names_scores.sort(key=getscore_int, reverse=True)
5
你可以使用csv模块,然后用sorted
来排序。
假设,scores1.txt文件里有以下内容
Richard,100
Michael,200
Ricky,150
Chaung,100
测试
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