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

查看:32
本文介绍了为什么我不能为 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'])

数据.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天全站免登陆