替换csv文件python的第一行

时间:2013-06-27 23:42:15

标签: python csv

我需要替换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

我需要复制一列并创建一个新标题,因此最终输出看起来像这样(注意数据1重复):

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)

1 个答案:

答案 0 :(得分:3)

您需要做的就是跟踪找到要复制的列的位置,然后添加它。例如:

# ...
# for ...

    if heading == 'mail':
        headers[index] = "Username"
    elif heading == 'data1':
        data_1_index = index

headers.insert(data_1_index, 'data1')

我假设你也想要复制每行中的值。但那也很容易。

for row in r:
    row.insert(data_1_index, row[data_1_index])
    w.writerow(row)

总而言之,这是一个完整的程序,可以完成您想要的任务(

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] = "Username"
        elif heading == 'data1':
            data_1_index = index
    headers.insert(data_1_index, 'data1')

    w = csv.writer(outfile, delimiter=',', quotechar='"')
    w.writerow(headers)
    for row in r:
        row.insert(data_1_index, row[data_1_index])
        w.writerow(row)