为什么不能为csv.Reader重复“for”循环? (蟒蛇) [英] Why can't I repeat the 'for' loop for csv.Reader? (Python)

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

问题描述

我是Python的初学者。我现在想弄清楚为什么第二个for循环不工作在以下脚本。我的意思是,我只能得到第一个'for'循环的结果,但没有从第二个。我复制和粘贴我的脚本和数据csv在下面。



如果你告诉我为什么会这样,以及如何使第二个for循环也很有用。



我的SCRIPT:

  import csv 

file =data.csv

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

阅读:
print(e ['a'])

for e in阅读:
print(e ['b'])



data.csv:

  a,b,c 
tree,bough,trunk
动物,腿,树干
鱼,鳍,身体


解决方案

csv reader是文件的迭代器。一旦你通过它一次,你读到文件的结尾,所以没有更多的读。如果你需要再次通过它,你可以寻找到文件的开头:

  fh.seek(0)

这会将文件重置为开头,以便您可以再次读取。



如果文件不是太大,你需要对数据做几件事,你也可以把整个东西读入一个列表:

  data = list(read)

可以使用 data 做你想要的。


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.

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.

My SCRIPT:

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":

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

解决方案

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.

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)

Then you can do what you want with data.

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

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