How to iterate over a specific range of strings using Python csv reader?

How to skip a specific range of lines using Python csv reader?

The following code goes through all the lines:

with open(trainFile, 'rt') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print (', '.join(row)) 

I want to sing only from the set (from i to j).

+6
source share
3 answers

You can use itertools.islice :

 import itertools i, j = 10, 20 with open(trainFile, 'rt') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in itertools.islice(spamreader, i, j+1): print (', '.join(row)) 

Alternative (the following code is possible because csv.reader accepts an iterable):

NOTE : only works when CSV lines do not contain a new line.

 import itertools i, j = 10, 20 with open(trainFile, 'rt') as csvfile: spamreader = csv.reader(itertools.islice(csvfile, i, j+1), delimiter=' ', quotechar='|') for row in spamreader: print (', '.join(row)) 
+7
source

Use islice , for example:

 rows_1_to_50 = itertools.islice(spamreader, 0, 50) for row in rows_1_to_50: pass 
+2
source

Another implementation of itertools using dropwhile and takewhile

 from itertools import takewhile, dropwhile trainFile = 'x.1' low_lim = 3 high_lim = 6 with open(trainFile, 'rt') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') g = (x for x in enumerate(spamreader, 1)) g = dropwhile(lambda x: x[0] < low_lim, g) g = takewhile(lambda x: x[0] <= high_lim, g) for row in g: print (', '.join(row[1])) 
+1
source

Source: https://habr.com/ru/post/954684/


All Articles