Python程序来计算文件中得分的平均值

时间:2019-02-13 19:24:22

标签: python-3.x

我写了一个程序来计算csv文件中每个人的平均得分:

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

但是它现在正在工作 请帮帮我!

我的csv文件如下:

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:参数1必须具有“写入”方法

2 个答案:

答案 0 :(得分:1)

行:

with open(output_file_name, mode='w') as w:
                w = csv.writer(output_file_name, delimiter= ...

您会看到两次定义w。一次是文件描述符,然后是csv编写器。

您需要将w(描述符)作为第一个参数传递给csv.writer()。这就是为什么我认为它给您一个错误。您将str作为第一个没有.write()的参数。

答案 1 :(得分:0)

这将起作用。请注意,这些值被读取为字符串,因此您需要先将它们转换为值,然后再取平均值,如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')