How to find specific row in Python CSV module

15.1k views Asked by At

I need to find the third row from column 4 to the end of the a CSV file. How would I do that? I know I can find the values from the 4th column on with row[3] but how do I get specifically the third row?

4

There are 4 answers

0
MrAlexBailey On BEST ANSWER

You could convert the csv reader object into a list of lists... The rows are stored in a list, which contains lists of the columns.

So:

csvr = csv.reader(file)
csvr = list(csvr)
csvr[2]     # The 3rd row
csvr[2][3]  # The 4th column on the 3rd row.
csvr[-4][-3]# The 3rd column from the right on the 4th row from the end
0
AudioBubble On

You could keep a counter for counting the number of rows:

counter = 1
for row in reader:
    if counter == 3:
        print('Interested in third row')
    counter += 1
0
alec_djinn On

This one is a very basic code that will do the job and you can easily make a function out of it.

import csv

target_row = 3
target_col = 4

with open('yourfile.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    n = 0
    for row in reader:
        if row == target_row:
            data = row.split()[target_col]
            break

print data
0
martineau On

You could use itertools.islice to extract the row of data you wanted, then index into it.

Note that the rows and columns are numbered from zero, not one.

import csv
from itertools import islice

def get_row_col(csv_filename, row, col):
    with open(csv_filename, 'rb') as f:
        return next(islice(csv.reader(f), row, row+1))[col]