I want to copy rows 3-5 to a new csv file.
I can get the following code to copy the whole file to the new file but the only detail I have found about grabbing arbitrary rows consists of piecing array index numbers like in line 4 below. This may be helpful at some point, but right now I want the whole row, or a range of rows.
I am pretty sure it is a simple thing, but apparently nobody else is writing about it.

    with open(filename, 'rb') as f:                         #This is scaffolding to see if the 
        reader = csv.reader(f)                              #read function worked  
        for row in reader:
            print("This is the header block", row[0], row[1])  
    with open('t_'+filename, 'wb') as title:                #This should be the start of the real code.
        writer = csv.writer(title)
        with open(filename, 'rb') as mycsv:
            reader = csv.reader(mycsv)
            for row in reader:
                writer.writerow(row)                        # I only want rows 3-5  
            for counter,row in enumerate(reader):
                if counter<3: continue
                if counter>5:break
                writer.writerow(row)                        # I only want rows 3-5  

This should work.

import csv

with open('test.csv', 'rb') as f,open('out.csv', 'wb') as f_out:
     reader = csv.reader(f)
     writer = csv.writer(f_out)
     for row in reader:
        writer.writerow((row[3], row[5]))

slate: "counter, row in enumerate reader" worked great.
snippsat: "writer.writerow((row[3], row[5]))" wrote just index 3 and 5 for each row, but it still wrote all rows. That is going to come in handy when I am sorting a subset of the columns for the next step in the report generation.

This article has been dead for over six months. Start a new discussion instead.