w.writerow完成后,python重命名标题行

时间:2016-06-29 02:21:27

标签: python

在下面的脚本中,我无法弄清楚如何重命名或" faux-rename"标题。

import csv,time,string,os

print "rendering report.  This will take a few minutes..."

raw_report = "\\\\network\\x\\RAWREPORT.csv"
today = time.strftime("%Y-%m-%d")

fields = ["As of Date", "EB", "Cycle", "Col", "APP Name", "Home Country" ]

with open(raw_report) as infile, open("c:\\upload\\test_" + today + ".csv", "wb") as outfile:
    r = csv.DictReader(infile)
    w = csv.DictWriter(outfile, fields, extrasaction="ignore")
    w.writeheader()
    for row in r:
        w.writerow(row)

这个脚本工作正常,它有一个.csv中有6列,大约有90列,但是为了只将fields中的那6列写入我的输出文件,我需要按名称调用它们。

但是,我需要它们最终被命名为不同的东西。(例如 - "order_date", "phone_number"...而不是"As of Date", "EB")。

我尝试了跳过第一行并编写自己的方法:

r = csv.DictReader(infile)
w = csv.DictWriter(outfile, fields, extrasaction="ignore")
next(r, None)
w.writerow(["order_date","phone_number",...])

但是python并不知道哪些列要复制到新文件中,因为名称不匹配。

我将如何去做我想做的事情?我可以按编号而不是按名称引用我想要复制的列,还是可以在复制完所有内容后返回并更改第一行的值?

1 个答案:

答案 0 :(得分:0)

我正在考虑这个错误。我可以将fields定义为要从中提取的原始文件中的列,但我不需要将它们包含在输出文件中,因为它们是两个单独的文件。

此代码有效:

fields = ["As of Date", "EB", "Cycle", "Col", "APP Name", "Home Country" ]
with open(raw_report) as infile, open("c:\\upload\\test_" + today + ".csv", "wb") as outfile:
    r = csv.DictReader(infile)
    w = csv.DictWriter(outfile, fields, extrasaction="ignore")
    #w.writeheader() #remove the writeheader command

    #write our custom header
    wtr = csv.writer( outfile )    
    wtr.writerow(["order_date", "phone_number", etc....])

    #then, write the rest of the file
    for row in r:
        w.writerow(row)