post output to new line of text file everytime

Question:

everytime i run my code it overwrites to first line of output.txt.
How can i make it so it writes to a new line every time?

def calculate_averages(input_file_name, output_file_name):
with open(input_file_name) as f:
    reader = csv.reader(f)
    for row in reader:
        name = row[0]
        these_grades = list()
        for grade in row[1:]:
            these_grades.append(int(grade))
        with open(output_file_name, 'w') as external_file:
            print(name, mean(these_grades), end='n', file=external_file)
            external_file.close()
Asked By: Ehsan Abedi

||

Answers:

This is happening because you are reopening your file in "w" mode for each row, which will overwrite your file. You can open the file outside of the for loop to avoid this behaviour:

import numpy as np
import csv

def calculate_averages(input_file_name, output_file_name):
    with open(input_file_name) as f:
        reader = csv.reader(f)
        with open(output_file_name, 'w') as external_file:
            for row in reader:
                name = row[0]
                mean_of_grades = np.mean([int(x) for x in row[1:]])
                external_file.write(f"{name} {mean_of_grades}n")
Answered By: Nik

You can use a different mode for this:

Instead of with open(output_file_name, "w") as external_file:,
Use with open(output_file_name, "a") as external_file.

"a" stands for append, which will append the text to the end of the file.

I hope I understood your question right.

Answered By: Genius1512
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.