对文件中的某些信息进行排序

时间:2015-04-23 01:09:37

标签: python file sorting text-files

我正在制作一个程序,按字母顺序对文件进行排序,得分最高。该文件有4个这样的名称,由制表符分隔:

Jeff    12    17    16
Dan     23    21   18
John    12    10   20
Mary    13    24   24

这是我的代码:

with open("file.txt","r") as f:
    lines = f.readlines()
    lines.sort()
    fields = [line.split() for line in f]
    name, grades = fields[0], fields[1:]
    grades = [int(grade) for grade in grades]
    grades.sort()
    highest = max(grades)
with open('file.txt','w') as fout:
    for el in lines:
        fout.write('{0}\n'.format(' '.join(el)))
with open('file.txt','r') as fsort:
    for line in fsort:
        print(line[:-1])
    fsort.close()

我不断收到错误,例如列表值超出范围;对于野外线。有人可以给我一个解决方案,以便这段代码有效吗?

1 个答案:

答案 0 :(得分:1)

您需要使用fields = [line.split() for line in lines],而不是in f。调用f.readlines()时,文件指针最终会移动到末尾,这意味着fields是一个空列表。

然而,我有一种感觉name, grades = fields[0], fields[1:]不会做你想要的。以下内容应确保namegrades存储您想要的内容(根据提问者的要求进行大量修改):

with open("class6Afile.txt","r") as f:
    lines = f.readlines()
lines.sort()
with open('class6AfileOut.txt','w') as fout:
    for line in lines:
        fields = line.split()
        name, grades = fields[0], fields[1:]
        grades = [int(grade) for grade in grades]
        grades.sort()
        highest = max(grades)
        grades = [str(grade) for grade in grades]
        print name, grades
        fout.write('{0} {1}\n'.format(name, ' '.join(grades)))