import csv import sys import operator father = [] children = '' valp = 0 valc = 0 valcc = 0 valpp = 0 valpag_tot = 0 valcon_tot = 0 valpagp_tot = 0 valconp_tot = 0 old_numdoc = '0' old_magazzino = 0 my_list = [] with open("C:/Users/Matteo/Downloads/AMBRIABLR.csv", mode='r') as csv_file: csv_reader = csv.DictReader(csv_file,delimiter=";") sortedlist = sorted(csv_reader, key=operator.itemgetter("bcnumdoc"), reverse=False) line_count = 0 for row in sortedlist: if row['valpag']: valp = float(row['valpag'].replace(',', '.')) if row['valcon']: valc = float(row['valcon'].replace(',', '.')) if row['valpagp']: valpp = float(row['valpagp'].replace(',', '.')) if row['valconp']: valcc = float(row['valconp'].replace(',', '.')) if row["bcnumdoc"] != old_numdoc: father.append([old_numdoc, row["bctipdoc"], children, float(valcon_tot), float(valpag_tot),float(valconp_tot), float(valpagp_tot)]) #print(f'valpag_tot{valcon_tot} -Numero { row["bcnumdoc"]} - {old_numdoc} ') valpag_tot = valp # Start total for the new document valcon_tot = valc # Start total for the new document valpagp_tot = valpp # Start total for the new document valconp_tot = valcc # Start total for the new document print(f'Numero {old_numdoc} - {valcon_tot} ({valc}) - PADRE') children = row["cudescri"] old_numdoc = row["bcnumdoc"] line_count += 1 else: children += row["cudescri"] children += " " old_numdoc = row["bcnumdoc"] valpag_tot += valp valcon_tot += valc valpagp_tot += valpp valconp_tot += valcc print(f'Numero {old_numdoc} - {valcon_tot} ({valc}) - FIGLIO') line_count += 1 # Aggiungi l'ultimo documento processato #father.append([old_numdoc, row["bctipdoc"], children, valcon_tot, valpag_tot]) # Funzione di ricerca lineare def iterative_linear(arr, n, key_element): for x in range(n): if arr[x] == key_element: return x return -1 class ReportingDict: def __init__(self, d): self._d = d def __getitem__(self, key): try: return self._d[key] except KeyError: raise KeyError(f'{key!r} is missing from {self._d!r}') # Scrivi su file di output with open(sys.argv[1], 'wt') as f: writer = csv.writer(f,delimiter=";") writer.writerow(('Num doc', 'Serie', 'Descrizione', 'Valcon', 'Valpag', 'Valconp' , 'Valpagp')) for i in father: writer.writerow(i)