Skip to main content
 首页 » 编程设计

Python之遍历 csv 文件并检查下一行

2024年10月24日9xxx_UU

我想遍历 csv 文档并经常检查下一行的值,但坚持使用相同的行号。 .next() 正在跳过一行,这对我不起作用,除非我能以某种方式再次返回。有没有一种简单的方法可以做到这一点?我尝试了成对/循环,但如果文件很大,它会花费很长时间。 我的示例代码是:

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() 

请您参考如下方法:

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? 

我猜……也许吧?