Reputation: 27
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
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,
Upvotes: 1