Adriano10 Adriano10 - 2 months ago 8
Python Question

Excel cell values filled with 0

The part of code shown below

import collections
import csv
import sys


with open("321.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method.
for r in cr:
d[r[0]].append(r[1]) # fill dict


with open("sorted output.csv","w") as f:

cr = csv.writer(f,sys.stdout, lineterminator='\n')

od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value
for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs
v = [ord(i) for i in v] # convert letters into numbers

cr.writerow(v)


Gives me this output:

enter image description here

I want to fill all empty cells in the region: (A1::X30) with 0s.(Each time the cells that should be filled with 0s are defined by the length of the largest row. e.g. if the largest row had elements up until column Y the empty cells that should be filled with 0s would be in the region (A1::Y30))

Can you help?

Answer

I have not tested but perhaps this?

import collections
import csv
import sys

max_len = 0
with open("321.csv","r") as f:
    cr = csv.reader(f,delimiter=",")
    d=collections.defaultdict(lambda : list())
    header=next(cr)   # read title. Retrieve the next item from the iterator by calling its __next__() method.
    for r in cr:
        d[r[0]].append(r[1])   # fill dict
        max_len = max(len(d[r[0]]), max_len)

with open("sorted output.csv","w") as f:

    cr = csv.writer(f,sys.stdout, lineterminator='\n')

    od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value
    for k,v in od.items():  #The method items() returns a list of dict's (key, value) tuple pairs
        v = [ord(i) for i in v] + [0]*(max_len - len(v))  # convert letters into numbers

        cr.writerow(v)
Comments