Adding column in CSV python and enumerating it

user3454635 picture user3454635 · Apr 24, 2014 · Viewed 8.8k times · Source

my CSV looks like

John,Bomb,Dawn
3,4,5
3,4,5
3,4,5

I want to add ID column in front like so:

ID,John,Bomb,Dawn
1,3,4,5
2,3,4,5
3,3,4,5

using enumerate function, but I don't know how. Here's my code so far:

import csv

with open("testi.csv", 'rb') as input, open('temp.csv', 'wb') as output:
        reader = csv.reader(input, delimiter = ',')
        writer = csv.writer(output, delimiter = ',')

        all = []
        row = next(reader)
        row.append('ID')
        all.append(row)
        count = 0
        for row in reader:
                count += 1
                while count:
                        all.append(row)
                        row.append(enumerate(reader, 1))
                        break
        writer.writerows(all)

And the output comes all wrong:

John,Bomb,Dawn,ID
3,4,5,<enumerate object at 0x7fb2a5728d70>
3,4,5,<enumerate object at 0x1764370>
3,4,5,<enumerate object at 0x17643c0>

So the ID comes in the end, when it should be in the start, and it doesn't even do the 1,2,3. Some weird error comes out.

Answer

The bat picture The bat · Apr 24, 2014

I can suggest the code below to solve your question:

import csv

with open("testi.csv", 'rb') as input, open('temp.csv', 'wb') as output:
    reader = csv.reader(input, delimiter = ',')
    writer = csv.writer(output, delimiter = ',')

    all = []
    row = next(reader)
    row.insert(0, 'ID')
    all.append(row)
    for k, row in enumerate(reader):
        all.append([str(k+1)] + row)
    writer.writerows(all)

More compact code can be:

all = [['ID'] + next(reader)] + [[str(k+1)] + row for k, row in enumerate(reader)]

UPDATE (some explanation):

Your have wrong enumerate function understanding. enumerate should be used in for loop and when you iterate over enumerate function result you get the sequence of the tuples where first item is ordered number of item from list and the second is item itself.

But enumerate function return is object (docs) so when you try to convert it to string it call __repr__ magic method and cast enumerate object to <enumerate object at ...>.

Another words, enumerate helps to avoid additional counters in loops such as your count += 1 variable.

Also you have a very strange code here:

while count:
    all.append(row)
    row.append(enumerate(reader, 1))
    break

this part of code never can't be performed more than one time.