Search code examples
pythoncsvpathoptparse

optparse csv.reader


Can somebody help me, I'm trying to link an optparse with a csv reader, but I have been unable to do so. Below is my code:

import csv
from optparse import OptionParser

parser = OptionParser()
parser.add_option('--i1', action='store', type='string', dest='input1file', help='[REQUIRED] The input .csv file path.')
(options, args) = parser.parse_args()
input1file = options.input1file

data = csv.reader(open('input1file','r'))
temp = open('C:\Practice\output_edited.csv','a')
for column in data:
    temp.write(column[0]+','+column[len(column)-1]+'\n')
    print column[0]+','+column[len(column)-1]+'\n'
temp.close()

I don't know how to connect the add_option part so that the user can type in the filename path. Thanks!

I updated my code. Still can't get it working though.

Update1:

import sys
import csv
from optparse import OptionParser

parser = OptionParser()
parser.add_option('--i1', action='store', type='string', dest='input1file', help='[REQUIRED] The input .csv file path.')
(options, args) = parser.parse_args()
input1file = options.input1file

try:
    input1file = args[1]
except IndexError:
    sys.exit("Input file required, none given")

data = csv.reader(open(sys.args[1],'r'))
temp = open('C:\Practice\output_edited.csv','a')
for column in data:
    temp.write(column[0]+','+column[len(column)-1]+'\n')
    print column[0]+','+column[len(column)-1]+'\n'
temp.close()

Solution

  • If you don't specify --i1 on the command line, options.input1file is None, since you don't provide a default value.

    myscript.py --i1 input.txt
    

    Since --i1 is required, it really shouldn't be an option (since it is not optional). Take the input file from args, instead:

    parser = OptionParser()
    (options, args) = parser.parse_args()
    try:
        input1file = args[0]
    except IndexError:
        sys.exit("Input file required, none given")
    

    Or, as mgilson suggested, use argparse instead. It supports named positional parameters.