user3821329
user3821329

Reputation: 317

how to iterate through consecutive lines of a csv file

Sorry for the rookie question. I'm trying to iterate through consecutive (tuples) lines of a csv file in python. what I'm trying is this:

with open ('my_file.csv','rb') as f_obj:
    reader=csv.reader(f_obj)
    for f_row , s_row in zip(reader , reader[1:]):
          do something

it does not work with izip as well. Thanks in advance.

Upvotes: 1

Views: 141

Answers (1)

tobias_k
tobias_k

Reputation: 82899

A csv.reader in an iterator, and as such it can only be read once, then it's exhausted. Also, an iterator is not indexable, so zip(reader , reader[1:]) does not work.

I suggest you use itertools.tee to copy the reader, skip one line on one of the readers, and then zip those:

with open('my_file.csv') as f_obj:
    reader1, reader2 = itertools.tee(csv.reader(f_obj))
    next(reader2) # skip first line in reader2
    for f_row , s_row in zip(reader1, reader2):
          print f_row, s_row

For input file containing numbers 1 through 5 on separate lines, output is

['1'] ['2']
['2'] ['3']
['3'] ['4']
['4'] ['5']

Upvotes: 1

Related Questions