I have a file "list1" that contain Name, Surname, Note1, Note2, like this:
DUPOND, John, 12, 10
JAMES, Fil, 8, 10
KYLE, Gregor, 17, 7
I want to write a Python script to display in another file called "list2", the content of "list1" but sorted and with the average of the 2 notes in the format : Surname, Name, Note1, Note2, Average like this:
John, DUPOND, 12, 14, 13
JAMES, Fil, , 8, 10, 9
KYLE, Gregor, 17, 7, 12
Do you have advice to give ?
I have tested this code it's only display the content of my file in square bracket, how can i make the average of the 2 value and put it in another file?
import sys
import csv
with open(sys.argv[1], newline='') as f:
reader = csv.reader(f)
for row in reader:
statistics.mean(xs)
print(row)
The steps involved here are:
int
; csv
reads them as str
)import sys
import csv
import statistics
with open(sys.argv[1], newline='') as inf, open(sys.argv[2], 'w', newline='') as outf:
writer = csv.writer(outf)
for name, surname, *values in csv.reader(inf): # Read name first, surname second, then collect values
writer.writerow([surname, name, *values, statistics.mean(map(int, values))]) # Write surname first, then name, then values, then average
This works even if the number of values is something other than two, since the unpacking handles all extra values by collecting them into the values
list
, however many there may be.