2013-04-24 97 views
1

我想創建一個可導入的模塊來刪除一系列的列(特別是我正在使用的文件中的列73-177)。我試圖編輯這個文件的I/O代碼是爲刪除基於字段名稱的列而編寫的。我想修改此代碼以刪除csv文件中的列73-177。我需要做什麼來完成這個任務?刪除csv列的範圍

 
def removeColumns(num1, num2, inputFILE, FileName): 
    inPUTfile = open(inputFILE, 'r') 
    outPUTfile = open(FileName, 'w') 
    line = inPUTfile.readline() 
    while line: 
      # Delete Specified columns. First column range number, second column range number (+1) 
      lineList = line.split('\t') 
      removeCOL = "Calendar-Year" 
      i = 0 
      while lineList[i] != removeCOL: #(linesout?): 
       i = i + 1 
      lineList.pop(i) #remove these fields from the list.append 
      #write modified fields 
      remove = "\t".join(lineList) 
      outPUTfile.write(line) #write the new field names outfile 
      for line in inPUTfile: #remove field i from each remaining line and write it in the output file &modify input line 
       lineList = line.split() #convert to a list 
       lineList.pop(i) #remove fields from the list 
       line = '\t'.join(lineList) 
       line = line + '\n' #add a carriage return to the end of the row 
       outPUTfile.write(line)# Write the modified line in the output file 
      inPUTfile.close() #close the input file 
      outPUTfile.close() #close the output file 
    return outPUTfile 
    print outPUTfile 

回答

4

我意識到你問過如何修改原始代碼,但在這裏我真的認爲它會更容易理解如何以不同的方式做到這一點。 Python有一個有用的csv模塊,它可以爲你處理很多工作。喜歡的東西:

import csv 

remove_from = 2 
remove_to = 5 

with open("to_delete.csv", "rb") as fp_in, open("newfile.csv", "wb") as fp_out: 
    reader = csv.reader(fp_in, delimiter="\t") 
    writer = csv.writer(fp_out, delimiter="\t") 
    for row in reader: 
     del row[remove_from:remove_to] 
     writer.writerow(row) 

會變成

$ cat to_delete.csv 
a b c d e f g 
1 2 3 4 5 6 7 
8 9 10 11 12 13 14 
15 16 17 18 19 20 21 

$ cat newfile.csv 
a b f g 
1 2 6 7 
8 9 13 14 
15 16 20 21 
+0

我試圖運行的代碼,並遺憾的是沒有刪除列。我是一個使用python腳本編寫的初學者,但是我們的目標是定義一個從任何csv文件中刪除一系列列的過程 – user2316620 2013-04-24 17:50:16

+0

然後第一步肯定會理解'csv'模塊。如上所示,該代碼應該適用於製表符分隔的csv文件;把它變成一個函數是微不足道的。反而發生了什麼?你收到錯誤信息了嗎? – DSM 2013-04-24 17:59:04

+0

沒有錯誤消息。它似乎在python中運行得很好(完全按照提供的代碼使用代碼),但是當我打開新的csv文件來檢查它時,列仍然存在。 – user2316620 2013-04-24 18:08:38