Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading