更改列ord

2024-04-16 15:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

$ 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

Tags: csvinputoutputfirstnamejohncatsalesdoe