I need to replace the column headings in a CSV file, where I don't know the order or number of columns. For example the file could look like this:
DN cn sn Name mail depart mobile
data1 data2 data3 data4 data5 data6 data7
or this
DN cn depart mobile sn
data1 data2 data3 data4 data5
AND I need to copy one column and create a new heading, so the final output would look something like this (notice data1 is repeated):
user email phone depar mobile sn
data1 data1 data2 data3 data4 data5
I am going 'round in circles with this one. Using
import csv
with open('test.csv', 'rb') as csvfile:
r = csv.reader(csvfile, delimiter=',', quotechar='"')
headers=r.next()
for index, heading in enumerate(headers):
if heading == 'mail':
headers[index] = "Username"
I can change the column headings fine, and either write it to a new file or to the existing one, but then how do I add the extra column?
SOLUTION
Thanks to abarnert's answer below I am now using this code which works like a charm:
import csv
with open('test.csv', 'rb') as infile, open('out.csv', 'wb') as outfile:
r = csv.reader(infile, delimiter=',', quotechar='"')
headers=r.next()
for index, heading in enumerate(headers):
if heading == 'mail':
headers[index] = "WorkEmail"
username_index = index
headers.insert(username_index, 'Username')
w = csv.writer(outfile, delimiter=',', quotechar='"')
w.writerow(headers)
for row in r:
if len(row) >= username_index:
row.insert(username_index, row[username_index])
w.writerow(row)