Skip to content
Advertisement

post output to new line of text file everytime

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

Advertisement

Answer

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")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement