Search code examples
pythonfile-writing

Writing Lines to a Different File


I am reading content from a file (scores.txt) and I have formatted the data that I need from it and I would like to write those lines to a new file. The new file I will be writing to is top_scores.txt. Below is the code for the desired output. I am just not entirely sure how to print to the file.

infile = open('scores.txt', 'r')
lineList = sorted(infile.readlines())

for lines in lineList:
    newLine = lines.replace('\n', '')
    splitLines = newLine.split(',')
    studentNames = splitLines[0]
    studentScores = splitLines[1:]
    studentsList = []
    for i in studentScores:
        studentsList.append(int(i))
    topScore = max(studentsList)
    print(studentNames.capitalize() + ': ', studentsList, 'max score =', int(topScore))

Sample from scores.txt:

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

Sample for desired input for new file:

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


Solution

  • Here is a correct way to achieve what you want :

    with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", '\
    w') as outfile2:
        lineList = sorted(infile.readlines())
        for lines in lineList:
            newLine = lines.replace('\n', '')
            splitLines = newLine.split(',')
            studentNames = splitLines[0]
            studentScores = splitLines[1:]
            studentsList = []
            for i in studentScores:
                if i == '':
                    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 that I used two ways to print the result :

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

    Also note that I used a with statement like jDo suggested.

    This way, it permits to open a file and to automatically close it when exiting the block.

    EDIT :

    Here is a version that is even shorter :

    with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", 'w') as outfile2:
        lineList = sorted(infile.readlines())
        for lines in lineList:
            lines = lines.replace('\n', '').split(',')
            studentScores = lines[1:-1]
            studentsList = [int(i) for 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")