How can I select only a particular row in a CSV file?
<p>I have a little program that just needs to read one (and only one) row from a csv file and write the column values to a series of files.  The program has three system arguments: the path to the data file, the job id (uuid), and the target row number, i.e. the row in the csv that I want to parse.  It's not working, how can I fix it?</p>

<pre><code>import csv
import sys
import itertools

f = sys.argv[1]
uuid = sys.argv[2]
target_row = sys.argv[3]
tmpdir="/tmp/pagekicker/"
folder = tmpdir+uuid

destination1 = folder + '/csv/row.editedby'
destination3 = folder + '/csv/row.booktitle'
destination4 = folder + '/csv/row.seeds'
destination5 = folder + '/csv/row.imprint'
f = open(f, 'rb')
f1 = open(destination1, 'w')
f3 = open(destination3, 'w')
f4 = open(destination4, 'w')
f5 = open(destination5, 'w')

target_row = int(target_row)
try:
    reader = csv.reader(f)  # creates the reader object
    for row in itertools.islice(reader,1,1):   # iterates the rows of the file in orders
            editedby = row[0] # we throw away column 2
            booktitle = row[2]
            print row[2]
            seeds = row[3]
            imprint = row[4]
            f1.write(editedby)
            f3.write(booktitle)
            f4.write(seeds)
            f5.write(imprint)
            f.close()      
            f1.close()
            f3.close()
            f4.close()
            f5.close()
finally:
    print 'done'
</code></pre>

<p>UPDATE: thanks Graham Bell for his suggested code. There are two "f5s" in the first line of his 'with' statement  My code now looks like this:</p>

<p>i</p>

<pre><code>mport csv
import sys
import itertools

f = sys.argv[1]
uuid = sys.argv[2]
target_row = sys.argv[3]
tmpdir="/tmp/pagekicker/"
folder = tmpdir+uuid
# os.mkdir(folder)

destination3 = folder + '/csv/row.booktitle'
destination1 = folder + '/csv/row.editedby'
destination4 = folder + '/csv/row.seeds'
destination5 = folder + '/csv/row.imprint'

with open(f, 'rb') as f, open(destination1, 'w') as f1, open(destination3, 'w') as f3, open(destination4, 'w') as f4, open(destination5, 'w') as f5:
    target_row = int(target_row)
    try:
        reader = csv.reader(f)  # creates the reader object
        for row in itertools.islice(reader,1,1):   # iterates the rows of the file in orders
            editedby = row[0] # we throw away column 2
            booktitle = row[2]
            print row[2]
            seeds = row[3]
            imprint = row[4]
            f1.write(editedby)
            f3.write(booktitle)
            f4.write(seeds)
            f5.write(imprint)
        except
            print 'done'
</code></pre>

<p>Without the except, it generates "unexpected unindent" when I run it.  With the except, it says that the except line is invalid syntax.</p>