4

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

1 回答 1

4

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

# ...
# 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)
于 2013-06-27T23:47:39.953 回答