Adding column in CSV python and enumerating it

主宰稳场 提交于 2019-12-06 05:09:18

问题


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.


回答1:


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.




回答2:


You should use insert() instead of append(). This will allow you to specify the index where you want to add the element.

Try this

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)
    count = 0
    for row in reader:
        count += 1
        row.insert(0, count)
        all.append(row)
    writer.writerows(all)



回答3:


You can do something like this:

import csv

with open('testi.csv') as inp, open('temp.csv', 'w') as out:
    reader = csv.reader(inp)
    writer = csv.writer(out, delimiter=',')
    #No need to use `insert(), `append()` simply use `+` to concatenate two lists.
    writer.writerow(['ID'] + next(reader))
    #Iterate over enumerate object of reader and pass the starting index as 1.
    writer.writerows([i] + row for i, row in enumerate(reader, 1))

enumerate() returns an enumerate object, that yield the index and item in a tuple one at a time, so you need to iterate over the enumerate object instead of writing it to the csv file.

>>> lst = ['a', 'b', 'c']
>>> e = enumerate(lst)
>>> e
<enumerate object at 0x1d48f50>
>>> for ind, item in e:
...     print ind, item
...     
0 a
1 b
2 c

Output:

>>> !cat temp.csv
ID,John,Bomb,Dawn
1,3,4,5
2,3,4,5
3,3,4,5


来源:https://stackoverflow.com/questions/23261852/adding-column-in-csv-python-and-enumerating-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!