python - Sorting certain info in a file -


i making program sorts file alphabetically highest score. file has 4 names separated tabs:

jeff    12    17    16 dan     23    21   18 john    12    10   20 mary    13    24   24 

this code:

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

i keep getting errors such list value out of range; field line. can give me solution code works?

you need use fields = [line.split() line in lines], not in f. f.readlines() called, file pointer moved end eventually, meaning fields empty list.

however, have feeling name, grades = fields[0], fields[1:] isn't going want to. following should make sure name , grades store want (large edit upon request of asker):

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

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -