为什么我不能为csv.Reader重复"for"循环? [英] Why can't I repeat the 'for' loop for csv.Reader?

查看:102
本文介绍了为什么我不能为csv.Reader重复"for"循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的初学者.我现在正在尝试弄清楚为什么第二个"for"循环在以下脚本中不起作用.我的意思是,我只能得到第一个"for"循环的结果,而第二个则没有任何结果.我在下面复制并粘贴了脚本和数据csv.

I am a beginner of Python. I am trying now figuring out why the second 'for' loop doesn't work in the following script. I mean that I could only get the result of the first 'for' loop, but nothing from the second one. I copied and pasted my script and the data csv in the below.

如果您告诉我它为什么会以这种方式运行以及如何使第二个"for"循环也起作用,这将很有帮助.

It will be helpful if you tell me why it goes in this way and how to make the second 'for' loop work as well.

我的脚本:

import csv

file = "data.csv"

fh = open(file, 'rb')
read = csv.DictReader(fh)

for e in read:
    print(e['a'])

for e in read:
    print(e['b'])

"data.csv":

"data.csv":

a,b,c
tree,bough,trunk
animal,leg,trunk
fish,fin,body

推荐答案

csv阅读器是文件的迭代器.遍历一次后,您将读取文件的末尾,因此不再需要阅读.如果您需要再次检查它,可以搜索到文件的开头:

The csv reader is an iterator over the file. Once you go through it once, you read to the end of the file, so there is no more to read. If you need to go through it again, you can seek to the beginning of the file:

fh.seek(0)

这会将文件重新设置为开头,因此您可以再次阅读.根据代码,可能还需要跳过字段名称标头:

This will reset the file to the beginning so you can read it again. Depending on the code, it may also be necessary to skip the field name header:

next(fh)

这对于您的代码来说是必需的,因为DictReader第一次使用该行来确定字段名称,因此不再需要这样做. csv的其他用途可能没有必要.

This is necessary for your code, since the DictReader consumed that line the first time around to determine the field names, and it's not going to do that again. It may not be necessary for other uses of csv.

如果文件不是太大,并且您需要对数据做几件事,那么您也可以将整个内容读入列表:

If the file isn't too big and you need to do several things with the data, you could also just read the whole thing into a list:

data = list(read)

然后,您可以使用data做您想做的事情.

Then you can do what you want with data.

这篇关于为什么我不能为csv.Reader重复"for"循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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