Home > Enterprise >  post output to new line of text file everytime
post output to new line of text file everytime

Time:09-12

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()

CodePudding user response:

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")

CodePudding user response:

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.

  • Related