Felix Leonte
Felix Leonte

Reputation: 27

Adding a column with the row number to csv file

I want to change the last column of my csv file to contain the row number.

My input file looks like this

Soup that is too hot,1,
Space Jam on VHS,1,
Space muffins,1,

And I would like it to look like this:

Soup that is too hot,1,
Space Jam on VHS,2,
Space muffins,3,

This is the code I have written so far:

import csv
inputfile = csv.reader(open('file.csv', 'r'))
outputfile = open("output_file.csv", 'w')
nr = 1
for row in inputfile:
    place = row[1].replace('1',str(nr))
    outputfile.write( place+'\n')
    nr += 1

If I change the row[0] to row[1], I only get the numbers, if I make it row[0], I don't see the columns.

Upvotes: 1

Views: 1900

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 99041

You can use:

import re

with open("csv_rename_lines.csv") as f, open("csv_rename_lines_new.csv", "w") as w:
    lines = list(f)
    w.write(lines[0]) # write headers to new file
    for n, l in enumerate(lines[1:], 1):
        w.write(re.sub(r"\d+,\s*$", str(n)+",\n", l))

card, id
Soup that is too hot,1,
Space Jam on VHS,2,
Space muffins,3,

Demo

Upvotes: 1

Related Questions