Remove or keep specific columns in csv file
Question: I have a simple script to either remove last n columns from csv file or to
keep first n columns only in csv file:

    
    
    from sys import argv
    import csv
    
    if len(argv) == 4:
      script, inputFile, outputFile, n = argv
      n = [int(i) for i in n.split(",")]
    else:
      script, inputFile, outputFile = argv
      n = 1
    
    with open(inputFile,"r") as fin:
      with open(outputFile,"w") as fout:
        writer=csv.writer(fout)
        for row in csv.reader(fin):
          writer.writerow(row[:n])
    

Example usage (remove last two columns): `removeKeepColumns.py sample.txt
out.txt -2`

How do I extend this to handle possibility to keep/remove specific set of
columns, e.g.:

  * remove columns 3,4,5
  * keep only columns, 1,4,6

I can split input arguments separted by comma into array, but don't know hot
to pass this to `writerow(row[])`

Links to scripts I used to create my example:

  * [Delete or remove last column in CSV file using Python](http://stackoverflow.com/questions/7245738/delete-or-remove-last-column-in-csv-file-using-python)
  * [Can sys.argv handle optional arguments?](http://stackoverflow.com/questions/9442313/can-sys-argv-handle-optional-arguments)
  * [What is the easiest way to convert list with str into list with int?](http://stackoverflow.com/questions/2424412/what-is-the-easiest-way-to-convert-list-with-str-into-list-with-int)


Answer: Well there was an accepted answer already, here's my solution:

    
    
    >>> import pyexcel as pe
    >>> sheet = pe.load("your_file.csv")
    >>> sheet.filter(sheet.ColumnFilter([1,4,5])) # the column indices to keep
    >>> sheet.save_as("your_filtered_file.csv")
    >>> exit()
    

Here is more details on
[filtering](http://pyexcel.readthedocs.org/en/latest/tutorial02.html)

