5

How can I only read from line 5000 to 6000 in this csv file for example? At this moment "for row in reader:" loops through all lines of course.

So I have the lines:

with open('A.csv', 'rt') as f:
     reader = csv.reader(f, delimiter=';')
     for row in reader:
           response = urllib2.urlopen(row[12])

This code is used to open specific url links.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Flex Texmex
  • 1,074
  • 2
  • 11
  • 23

2 Answers2

9

Because csv reader object supports iteration, you can simply use itertools.islice to slice any specific part that you want.

from itertools import islice

with open('A.csv', 'rt') as f:
     reader = csv.reader(f, delimiter=';')
     for row in islice(reader,5000,6000):
           response = urllib2.urlopen(row[12])
Mazdak
  • 105,000
  • 18
  • 159
  • 188
2

You can use a generator in your for loop with enumerate:

with open('A.csv', 'rt') as f:
     reader = csv.reader(f, delimiter=';')
     for row in (r for i, r in enumerate(reader) if 5000<=i<=6000):
           response = urllib2.urlopen(row[12])

Since csv.reader, enumerate and the generator expression itself are all generators, you will be only dealing with one at a time.

dawg
  • 98,345
  • 23
  • 131
  • 206