Python csv:写入文件时保留标头

时间:2012-07-24 10:05:11

标签: python csv

我编写了一个简单的函数,根据用户提供的CSV行数,通过添加或删除列来执行操作:

def sanExt(ifpath, ofpath):
    with open(ifpath, "rb") as fin, open(ofpath, "wb") as fout:
        csvin = csv.reader(fin)
        csvout = csv.writer(fout, delimiter=",")
        fline = csvin.next()
        if len(fline) == 33:
            for row in csvin:
                row.insert(10, "NULL")
                csvout.writerow(row)
            print "AG"
        elif len(fline) == 35:
            print "AI"
        elif len(fline) == 36:
            print "AJ"
        else:
            print "Unknown"

我已经停止了第一个if语句,只是为了确保我的代码正常运行。在这种情况下,该列已正确添加,但标题丢失。

如何确保每一行都写入文件,而不仅仅是[1:len(rows)]

我的方法是正确的pythonic方式来完成所需的工作吗?

2 个答案:

答案 0 :(得分:2)

如果您不需要csv.DictReader来通过列名进行访问,那么传统的解决方案基于以下内容:

with open('in.csv') as fin, open('out.csv', 'wb') as fout:
   csvin = csv.reader(fin)
   csvout = csv.writer(fout)
   try:
       header = next(csvin)
       csvout.writerow(header)
   except StopIeration as e:
       pass # empty file - either handle, or we'll just continue and drop out of loop

   for row in csvin:
       csvout.writerow(row) # do some real work here...

答案 1 :(得分:1)

使用csv.DictReader,csv.DictWriter及其writeheader()方法处理标题行,但代码很少。