循环csv.DictReader的行不止一次 [英] Loop over rows of csv.DictReader more than once

查看:159
本文介绍了循环csv.DictReader的行不止一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I open a file and read it with csv.DictReader. I iterate over it twice, but the second time nothing is printed. Why is this, and how can I make it work?

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

推荐答案

您在第一次迭代时就读取了整个文件,因此第二次读取时就没有东西了.由于您似乎没有第二次使用csv数据,因此计算行数并第二次仅遍历该范围会更简单.

You read the entire file the first time you iterated, so there is nothing left to read the second time. Since you don't appear to be using the csv data the second time, it would be simpler to count the number of rows and just iterate over that range the second time.

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数据,再次打开文件很简单.最有可能的是,您应该遍历第一次存储的某些数据,而不是再次读取文件.

If you need to iterate over the raw csv data again, it's simple to open the file again. Most likely, you should be iterating over some data you stored the first time, rather than reading the file again.

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

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

If you don't want to open the file again, you can seek to the beginning, skip the header, and iterate again.

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

这篇关于循环csv.DictReader的行不止一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆