2016-10-05 161 views
0

我對Python非常陌生,而且在刪除第25列後的標題列時遇到問題。還有8個額外的列沒有數據,所以我試圖刪除這些列。第1-25列有5萬個數據,剩下的列是空白的。我該怎麼做?我現在的代碼能夠清理文件,但我不能刪除標頭行[0]列之後25
感謝刪除標題行中的空白列

import csv 

my_file_name = "NVG.txt" 
cleaned_file = "cleanNVG.csv" 
remove_words = ['INAC-EIM','-INAC','TO-INAC','TO_INAC','SHIP_TO-inac','SHIP_TOINAC'] 


with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w',newline='') as outfile: 
    writer = csv.writer(outfile) 
    cr = csv.reader(infile, delimiter='|') 
    writer.writerow(next(cr)) #I think this is why is not working 
    for line in (r[0:25] for r in cr): 
     #del line [26:32] 
     if not any(remove_word in element for element in line for remove_word in remove_words): 
     line[11]= line[11][:5] 
     writer.writerow(line) 

回答

1

你發現有問題的線 - 所有你需要做只是打印你想要的標題。 next(cr)讀取標題行,但您將整行傳遞給writer.writerow()

而不是

writer.writerow(next(cr)) 

你想:

writer.writerow(next(cr)[:25]) 

[:25][0:25]是相同的在Python)

+0

哇,我收到了這一點,它拋出一個錯誤,這是原因其中一行有縮進錯誤,所以我認爲它是別的。謝謝!!這工作:) – Cesar