Python - 如何在读取csv文件时读取前面的行?

时间:2015-07-31 15:15:47

标签: python python-2.7 csv row readline

我想在excel表中读取行但是在我想要的时候,在阅读过程中,我想停止向前阅读,我想阅读前面的行(向后阅读)?我怎样才能再次前一行?

import csv

file = open('ff.csv2', 'rb')
reader = csv.reader(file)

for row in reader:
    print row

1 个答案:

答案 0 :(得分:0)

您始终可以将这些行存储在列表中,然后使用索引访问每一行。

import csv
file = open('ff.csv2', 'r')

def somereason(line):
    # some logic to decide if stop reading by returning True
    return False  # keep on reading

for row in csv.reader(file):
    if somereason(line):
        break

    lines.append(line)

# visit the stored lines in reverse
for row in reversed(lines):
   print(row)