我需要替换 CSV 文件中的列标题,我不知道列的顺序或数量。例如,该文件可能如下所示:
DN cn sn Name mail depart mobile
data1 data2 data3 data4 data5 data6 data7
或这个
DN cn depart mobile sn
data1 data2 data3 data4 data5
而且我需要复制一列并创建一个新标题,因此最终输出看起来像这样(注意 data1 重复):
user email phone depar mobile sn
data1 data1 data2 data3 data4 data5
我要在这个圈子里兜圈子。使用
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"
我可以很好地更改列标题,并将其写入新文件或现有文件,但是如何添加额外的列?
解决方案
感谢 abarnert 在下面的回答,我现在正在使用这个代码,它就像一个魅力:
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)