更改列顺序

时间:2012-10-15 10:36:32

标签: python csv

$ cat customer.csv
customerno, firstname, lastname, sales
23242, john, doe, 2345.00
23253, jane, doe, 1234.00
23221, greg, johnson, 2345.00
23210, howard, gardner, 2345.00

以下代码按预期工作,它会重新显示列顺序。

import csv
with open('customer2.csv', 'wb') as output:
    input = csv.reader(open('customer.csv', 'rb'))
    output = csv.writer(output, dialect=input.dialect)
    for line in input:
        line.reverse()
        output.writerow(line)

$ cat customer2.csv
 sales, lastname, firstname,customerno
 2345.00, doe, john,23242
 1234.00, doe, jane,23253
 2345.00, johnson, greg,23221
 2345.00, gardner, howard,23210

但我真正需要的不是4,3,2,1而是4,2,3,1序列。预期产出:

$ cat newfile.csv
 sales, lastname, firstname, lastname, customerno
 2345.00, john, doe, 23242
 1234.00, jane, doe, 23253
 2345.00, greg, johnson, 23221
 2345.00, howard, gardner, 23210

1 个答案:

答案 0 :(得分:4)

(customerno, firstname, lastname, sales) = line
outLine = (sales, firstname, lastname, customerno)
output.writerow(outLine)