小编典典

循环csv.DictReader的行不止一次

python

我打开一个文件,然后用读取csv.DictReader。我遍历了两次,但是第二次什么也没打印。为什么会这样,如何使它起作用?

with open('MySpreadsheet.csv', 'rU') as wb:
    reader = csv.DictReader(wb, dialect=csv.excel)
    for row in reader:
        print row

    for row in reader:
        print 'XXXXX'

# XXXXX is not printed

阅读 351

收藏
2021-01-20

共1个答案

小编典典

您是在第一次迭代时读取了整个文件,因此第二次读取时没有什么可剩下的。由于您似乎没有第二次使用csv数据,因此计算行数并第二次仅遍历该范围会更简单。

import csv
from itertools import count

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)
    row_count = count(1)

    for row in reader:
        next(count)
        print(row)

for i in range(row_count):
    print('Stack Overflow')

如果您需要再次遍历原始csv数据,则再次打开文件很简单。最有可能的是,您应该遍历第一次存储的某些数据,而不是再次读取文件。

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print(row)

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print('Stack Overflow')

如果您不想再次打开文件,则可以查找到开头,跳过标题,然后再次进行迭代。

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)

    for row in reader:
        print(row)

    f.seek(0)
    next(reader)

    for row in reader:
        print('Stack Overflow')
2021-01-20