如何在同一" for"中转到CSV文件的第一条记录。环?

时间:2014-04-22 06:00:32

标签: python csv

我问了一个类似的问题here,我得到的答案是使用seek()方法。现在我正在做以下事情:

with open("total.csv", 'rb') as input1:
    time.sleep(3)
    input1.seek(0)
    reader = csv.reader(input1, delimiter="\t")
    for row in reader:
       #Read the CSV row by row.

但是,我想导航到同一for循环中CSV 的第一条记录。我知道我的循环不会以这种方式终止,但这正是我想要的。我不希望for循环结束,如果它到达最后一条记录,我想导航回第一条记录并重新读取整个文件(并继续阅读)。我怎么做?

谢谢!

3 个答案:

答案 0 :(得分:1)

是否必须在for循环中?您可以像这样(未经测试)实现此行为:

with open("total.csv", 'rb') as input1:
    time.sleep(3)
    reader = csv.reader(input1, delimiter="\t")
    while True:
        input1.seek(0)
        for row in reader:
            #Read the CSV row by row.

答案 1 :(得分:1)

为简单起见,创建一个生成器:

def repeated_reader(input, reader):
    while True:
        input.seek(0)
        for row in reader:
            yield row

with open("total.csv", 'rb') as input1:
    reader = csv.reader(input1, delimiter="\t")
    for row in repeated_reader(input1, reader):
        #Read the CSV row by row.

答案 2 :(得分:0)

我实际上计算了CSV中的总行数,当我在最后一行时,我做了input1.seek(0)

row_count = sum(1 for row in csv.reader(open('total.csv')))
print row_count


row_count2 = 0

with open("total.csv", 'rb') as input1:
        time.sleep(3)
        input1.seek(0)
        reader = csv.reader(input1, delimiter="\t") 
        for row in reader:
            count += 1
            #Read the CSV row by row.
            if row_count2 == row_count:
                row_count2 = 0
                time.sleep(3)
                input1.seek(0)