Q:

Deleting a range of csv columns

I am trying to create an importable module to delete a range of columns (specifically columns 73-177 in the file I am working with).I am attempting to edit this file i/o code that is written for removing a column based on the field name. I want to modify this code to delete columns 73-177 in a csv file. What do I need to do to accomplish this?

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

A:

I realize that you asked how to modify the original code, but here I honestly think it'd be easier to understand how to do it a different way.  Python has a useful csv module which handles a lot of the work for you.  Something like:
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)

will turn
$ 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

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

