簡體   English   中英

Python csv:寫入文件時保留標頭

[英]Python csv: preserve headers when writing to file

我編寫了一個簡單的函數,根據用戶提供的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方式來完成所需的工作嗎?

如果您不需要通過列名訪問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...

使用csv.DictReader,csv.DictWriter及其writeheader()方法來處理帶有少量多余代碼的標題行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM