从python中的csv计算总和

时间:2017-09-25 10:53:27

标签: python csv

我必须从python中的csv文件计算两个参数(所有项目的总数或项目和总值)。这个问题要求我们阅读csv文件,按产品ID对列表进行排序,并通过在三个函数(main函数,read_products和print_product_info)中构造代码来显示信息。输出应该类似于:

Product ID: 123432
Description: Dell Venue Touchscreen Tablet
Unit Price: $184.99
Inventory Count: 29
Value: $ 5,364.71 

这是csv文件:

Id,Description,Price,Inventory Count
892373,Dell Chromebook 13,449.99,20
432999,Dell Silver Inspiron Laptop,790.00,15
123432,Dell Venue Touchscreen Tablet,184.99,29
563900,Dell Inspiron Desktop,379.00,10

这是我到现在所写的内容:

def read_products(products):
    products_list =[]
    my_file=csv.reader(open('products.csv'),delimiter=',')
    heading = next(my_file)
    ID, Description, Price, Inventory_Count = row
    sort=sorted(my_file, key=operator.itemgetter(0))
    for line in sort:
        products_list.append(row)
    return (products_list)

def main():
    total_number_of_items = 0
    total_value_of_all_assets = 0


if __name__ == "__main__":
    main()

每当我尝试在main函数中进行任何计算时,我在If__name__行中都会出错。如何在main函数中进行计算以对两个参数求和?
另外,如何以上述格式逐个打印产品信息?

2 个答案:

答案 0 :(得分:0)

首先,你将一个名为products的参数传递给函数read_products,你在函数内部没有使用它(我想你的意思是文件名?)。关于__main__错误,有助于追溯...

无论如何,你试过pandas吗?会让这更容易:

import pandas as pd

def read_products(filename):
    products = pd.read_csv(filename)
    # Sort by ID, you can use other columns as well
    products.sort_values(by='Id', inplace=True)
    return products

def main(filename):
    products = read_products(filename)
    total_value = products['Price'].sum()
    total_count = products['Inventory Count'].sum()

    print products
    print 'Number of items:', total_count
    print 'Total value:', total_value


if __name__ == '__main__':
    main('products.csv')

如果您不想/不能使用pandas,这是打印功能的另一种方法:

import csv
from operator import itemgetter

def read_products(filename):
    products = list(csv.reader(open(filename)))
    header = products[0]
    sorted_items = sorted(products[1:], key=itemgetter(0))
    sorted_products = [header] + sorted_items
    # NOTE: This is a list of lists, not a csv.reader instance
    return sorted_products

def print_table(table):
    for row in table[1:]:
        lines = ['{}: {}'.format(table[0][i], v) for i, v in enumerate(row)]
        string = '\n'.join(lines)
        print string, '\n'

def main(filename):
    products = read_products(filename)
    total_value = sum([float(row[2]) for row in products[1:]])
    total_count = sum([int(row[3]) for row in products[1:]])

    print_table(products)
    print '-------------------------------------'
    print 'Number of items:', total_count
    print 'Total value:', total_value

if __name__ == '__main__':
    main('products.csv')

希望它有所帮助。

答案 1 :(得分:0)

我明白了。有一些很难找到的语法错误。感谢大家的反馈。

def read_products(products):
    product_list = []
    with open(products, "r") as f:
        f_csv = csv.reader(f)
        headings = next(f_csv)
        for row in f_csv:
            product_list.append(row)
    return (product_list)


def main():
    products = read_products('products.csv')
    list.sort(products, key=operator.itemgetter(0), reverse=False)
    total_items = 0
    total_assets = 0
    for row in products:
        print('Product ID:', row[0])
        print('Description:', row[1])
        print('Unit Price:', row[2])
        print('Inventory Count:', row[3])
        print('Value:', (float(row[2]) * float(row[3])))
        print("\n")
        total_items = total_items + float(row[3])
        total_assets = total_assets + (float(row[2]) * float(row[3]))
    print('Total Number of items is', total_items)
    print('Total Value of all assets:', total_assets,end="\n")

if __name__ == "__main__":
    main()