python - Writing Lines to a Different File -


i reading content file (scores.txt) , have formatted data need , write lines new file. new file writing top_scores.txt. below code desired output. not entirely sure how print file.

infile = open('scores.txt', 'r') linelist = sorted(infile.readlines())  lines in linelist:     newline = lines.replace('\n', '')     splitlines = newline.split(',')     studentnames = splitlines[0]     studentscores = splitlines[1:]     studentslist = []     in studentscores:         studentslist.append(int(i))     topscore = max(studentslist)     print(studentnames.capitalize() + ': ', studentslist, 'max score =', int(topscore)) 

sample scores.txt:

pmas,95,72,77,84,86,81,74,\n

sample desired input new file:

pmas: [95,72,77,84,86,81,74], max score = 95\n

here correct way achieve want :

with open("scores.txt", 'r') infile, open("top_score.txt", 'w') outfile, open("top_score2.txt", '\ w') outfile2:     linelist = sorted(infile.readlines())     lines in linelist:         newline = lines.replace('\n', '')         splitlines = newline.split(',')         studentnames = splitlines[0]         studentscores = splitlines[1:]         studentslist = []         in studentscores:             if == '':                 break             studentslist.append(int(i))         topscore = max(studentslist)         result = "%s: %s,max score = %d" % (studentnames.capitalize(),                                             str(studentslist),                                             max(studentslist))         print(result)         print(result, file = outfile)         outfile2.write(result + "\n") 

note used 2 ways print result :

  • print() file parameter.
  • file.write() method.

also note used with statement jdo suggested.

this way, permits open file , automatically close when exiting block.

edit :

here version shorter :

with open("scores.txt", 'r') infile, open("top_score.txt", 'w') outfile, open("top_score2.txt", 'w') outfile2:     linelist = sorted(infile.readlines())     lines in linelist:         lines = lines.replace('\n', '').split(',')         studentscores = lines[1:-1]         studentslist = [int(i) in studentscores]         result = "%s: %s,max score = %d" % (lines[0].capitalize(),                                             str(studentslist),                                             max(studentslist))         print(result)         print(result, file = outfile)         outfile2.write(result + "\n") 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -