2013-04-24 102 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