Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - loop through csv file and check next line

Tags:

python

csv

I want to loop through a csv document and often check the next row for values, but stick to the same row number. The .next() is skipping a row, which won't work for me, unless I could go back again somehow. Is there a simple way in doing this? I tried the pairwise/cycle but it takes way too long if the file is big. My sample code is:

file1 = open("name.csv", 'rb')
reader = csv.DictReader(file1)
new_rows_list = []

for row in reader:
    if row['IsFixated'] == 'TRUE':
        new_row = [row['Result'], 'Fixation']
        new_rows_list.append(new_row)
    else:
        new_row = [row['Result'], 'Saccade']
        new_rows_list.append(new_row)
        nextRow = reader.next() # check for next row ??
        if nextRow['IsFixated'] == 'TRUE':
            new_rows_list = CheckPreviousPositions(new_rows_list)

file1.close()
like image 875
lemanou Avatar asked Aug 12 '26 02:08

lemanou


1 Answers

reader1,reader2 = itertools.tee(csv.DictReader(file1))
#this creates two copies of file iterators for the file
next(reader2) #skip first line in second filehandle
for line,next_line in itertools.izip(reader1,reader2):
    #do something?

I guess ... maybe?

like image 113
Joran Beasley Avatar answered Aug 13 '26 16:08

Joran Beasley