Reputation: 349
I wrote a program to calculate average of score of each person from csv file:
import csv
# For the average
from statistics import mean
from collections import OrderedDict
def calculate_averages(input_file_name, output_file_name):
with open(input_file_name, newline='') as f:
reader = csv.reader(f)
for row in reader:
with open(output_file_name, mode='w') as w:
w = csv.writer(output_file_name, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
li = list()
li[0] = row[0]
li[1] = mean(row[1:])
w.writerow(li)
calculate_averages('in.csv','out.csv')
but it's now working help me please!
and my csv file is like:
mandana,5,7,3,15
hamid,3,9,4,20,9,1,8,16,0,5,2,4,7,2,1
sina,19,10,19,6,8,14,3
sara,0,5,20,14
soheila,13,2,5,1,3,10,12,4,13,17,7,7
ali,1,9
sarvin,0,16,16,13,19,2,17,8
TypeError: argument 1 must have a "write" method
Upvotes: 0
Views: 394
Reputation: 3455
This will work. Note the values are read as strings, so you need convert them first to values before you take the mean, as done in vals = [float(val) for val in row[1:]]
import csv
from statistics import mean
def calculate_averages(input_file_name, output_file_name):
with open(input_file_name, mode='rt', newline='') as csv_in:
csv_content = csv.reader(csv_in)
with open(output_file_name, mode='wt', newline='') as csv_out:
csv_writer = csv.writer(csv_out, delimiter=',')
for row in csv_content:
vals = [float(val) for val in row[1:]]
csv_writer.writerow([row[0], mean(vals)])
if __name__ == '__main__':
calculate_averages('in.csv','out.csv')
Upvotes: 0
Reputation: 2766
the lines:
with open(output_file_name, mode='w') as w:
w = csv.writer(output_file_name, delimiter= ...
you can see you're defining w
twice. once as the file descriptor and then as the csv writer.
you need to pass w
(the descriptor) as the first argument to csv.writer()
. this is why i presume it's giving you an error. you're passing str
as the first arg which doesn't have a .write()
.
Upvotes: 1