Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV read specific row

Tags:

python

csv

I have a CSV file with 100 rows.

How do I read specific rows?

I want to read say the 9th line or the 23rd line etc?

like image 374
blue_zinc Avatar asked Oct 20 '14 11:10

blue_zinc


2 Answers

You could use a list comprehension to filter the file like so:

with open('file.csv') as fd:     reader=csv.reader(fd)     interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)] # now interestingrows contains the 28th and the 62th row after the header 
like image 118
ch3ka Avatar answered Sep 17 '22 13:09

ch3ka


Use list to grab all the rows at once as a list. Then access your target rows by their index/offset in the list. For example:

#!/usr/bin/env python  import csv  with open('source.csv') as csv_file:     csv_reader = csv.reader(csv_file)     rows = list(csv_reader)      print(rows[8])     print(rows[22]) 
like image 34
Alan W. Smith Avatar answered Sep 20 '22 13:09

Alan W. Smith