1

我编写了一个简单的函数,该函数根据用户提供的 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 方法吗?

4

2 回答 2

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...
于 2012-07-24T10:54:42.393 回答
1

使用 csv.DictReader、csv.DictWriter 及其writeheader()方法来处理带有少量多余代码的标题行。

于 2012-07-24T10:16:49.837 回答