读取csv文件并计算总和

时间:2015-06-02 04:40:09

标签: csv python-3.x

import glob
import csv

def read_with_csv(filename):
    data = []
    for x in csv.reader(open(filename, 'r')):
        data.append(x)            
    return data 

def calculate_sum(data_sample):
    total = 0
    for row in data_sample[1:]:
        price = float(row[9])
        total += price
    return total

files = [file for file in glob.glob("*.csv") if 'Invoice-Item-Adjustment_' in file]
data_from_csv = read_with_csv(files)
the_sum = data_from_csv(calculate_sum)
print(the_sum)

我在目录中有多个文件并读取列表并循环显示列中的金额并按月计算总金额。我有错误,不知道如何处理。

 Traceback (most recent call last):
      File "listing.py", line 18, in <module>
        data_from_csv = read_with_csv(files)
      File "listing.py", line 6, in read_with_csv
        for x in csv.reader(open(filename, 'r')):
    TypeError: invalid file: ['JEExport_20141201-20141218_Invoice-Item-Adjustment_20
    150208164027.csv', 'JEExport_20150116-20150128_Invoice-Item-Adjustment_201502021
    70516.csv'

]   

2 个答案:

答案 0 :(得分:0)

python中的列表推导会返回一个集合 - 而不是文件本身。

因此

files = [file for file in glob.glob("*.csv") if 'Invoice-Item-Adjustment_' in file]

返回名称中包含发票项目调整的文件列表。您必须逐个遍历文件然后进行处理。

答案 1 :(得分:0)

您的函数read_with_csv()将文件名作为参数而不是文件列表。因此,以下内容可能取决于您想要做什么

data_from_csv = [read_with_csv(file) for file in files]