Reputation: 411
I am not able to write data into csv file. I was able to separate the header and add new column and also was able to add the total scores, but seems like it is not working
Source File
name,Homework_1,Homework_2
Naveed,20,19
Mahvish,10,18
Target File
name,Homework_1,Homework_2,total
Mahvish,10,18,28.0
Naveed,20,19,39
import csv
def letterGrade(score):
if score >= 90:
letter = 'A'
elif score >= 80:
letter = 'B'
elif score >= 70:
letter = 'C'
elif score >= 60:
letter = 'D'
else:
letter = 'F' #fall through or default case
return letter
with open('marks.csv','r') as r:
csvReader=csv.reader(r)
header=next(csvReader)
header.append("total")
total=0
if header!=None:
for row in csvReader:
total=0
for index in range(1,3):
thisGrade = row[index]
if thisGrade == '':
thisGrade = 0.0 # change a nothing to a zero
else:
thisGrade = float(thisGrade)
total = total + thisGrade
percent = (total * 100.)/ 200. # out of a possible 200 points
gradeToReport = letterGrade(percent)
row.append(total)
print(row)
with open('marks_op.csv','w',newline='') as w:
csvWriter=csv.writer(w,delimiter=',')
csvWriter.writerow(i for i in header)
#csvWriter.writerows(row)
csvWriter.writerow(row)
Upvotes: 0
Views: 168
Reputation: 411
I have corrected the code. Thanks for solution Mike 67.
import csv
def letterGrade(score):
if score >= 90:
letter = 'A'
elif score >= 80:
letter = 'B'
elif score >= 70:
letter = 'C'
elif score >= 60:
letter = 'D'
else:
letter = 'F' #fall through or default case
return letter
with open('marks.csv','r') as r:
csvReader=csv.reader(r)
header=next(csvReader)
header.append("total")
with open('marks_op.csv','w',newline='') as w:
csvWriter=csv.writer(w,delimiter=',')
csvWriter.writerow(header)
total=0
if header!=None:
for row in csvReader:
total=0
for index in range(1,3):
thisGrade = row[index]
if thisGrade == '':
thisGrade = 0.0 # change a nothing to a zero
else:
thisGrade = float(thisGrade)
total = total + thisGrade
percent = (total * 100.)/ 200. # out of a possible 200 points
gradeToReport = letterGrade(percent)
row.append(total)
with open('marks_op.csv','a',newline='') as x:
csvWriter=csv.writer(x,delimiter=',')
csvWriter.writerow(row)
Upvotes: 0
Reputation: 11342
You're overwriting the output file in each loop iteration
with open('marks_op.csv','w',newline='') as w:
should be
with open('marks_op.csv','a',newline='') as w:
Upvotes: 1