Viewing file: csv_totalizer.py (1.07 KB) -rw-rw-r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
import sys import csv import os
def usage(): print " usage: python csv_totalizer.py <directory> | <directory>: directory where the csv files are"
def sumarize_products(filename, products): with open(filename) as file: reader = csv.reader(file, delimiter=';') for line in reader: for i in range(0, len(line), 4): try: item = line[i] count = int(line[i+1]) price = float(line[i+2].replace(".", "")) if item in products.keys(): products[item]['count'] += count products[item]['total'] += price*count else: products[item] = { 'count': count, 'price': price, 'total': price } except ValueError: pass
if __name__ == '__main__': if len(sys.argv) > 1: products = {} working_dir = sys.argv[1] files = [ file for file in os.listdir(working_dir) if file.endswith("csv") ] for filename in files: sumarize_products(filename, products)
for product, total in products.iteritems(): print "%s,%0.2f,%0.2f,%0.2f" % (product, total['count'], total['price'], total['total']) else: usage()
|