Python function: This is my code and I don\'t know how to add the column to the
ID: 3706880 • Letter: P
Question
Python function:
This is my code and I don't know how to add the column to the csv file:
def write_with_averages(read,write):
with open (read,'r') as f_in:
header = f_in.readline()
reader=csv.reader(f_in)
with open (write,'w') as f_out:
writer=csv.writer(f_out)
New_data=[]
for Name, Test1, Test2, Test3 in reader:
Total=(float(Test1)+float(Test2)+float(Test3))
average=Total/3
New_data.append(average)
Explanation / Answer
PYTHON CODE:
def write_with_average(read,write):
# opening the file for reading
file1=open(read)
# opening the file for writing the output
output=open(write,'w')
# writing the headers to the output file
output.write('Name,Test1,Test2,Test3,Average ')
# for every line in the file1
for number,line in enumerate(file1):
# skipping the header
if number == 0:
continue
# removing the spaces at the end and beginnging of the line
line=line.strip()
# splitting the line by comma
data=line.split(',')
# variable to store the total marks
total=0
# writing the Name to the output file
output.write(data[0]+',')
# calculating total
for mark in data[1:]:
total+=float(mark)
# writing the mark to the output file
output.write(mark+',')
# calculating the average
average=total/(len(data)-1)
# writing average to the output file
output.write(str(average)+' ')
# closing the files
output.close()
file1.close()
#testing
if __name__=='__main__':
# calling the function
write_with_average('random_grades.csv','grades_and_averages.csv')
CONTENTS OF random_grades.csv:
Name,Test1,Test2,Test3
Ila,1,67,64
Xavier,83,11,54
Phillip,39,95,16
CONTENTS OF grades_and_average.csv:
Name,Test1,Test2,Test3,Average
Ila,1,67,64,44.0
Xavier,83,11,54,49.333333333333336
Phillip,39,95,16,50.0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.