Python:如何使用DictReader两次? [英] Python: How do I use DictReader twice?

查看:534
本文介绍了Python:如何使用DictReader两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这感觉像一个非常基本的问题,但我不能在其他地方找到它。我是一个开始的Python用户。

This feels like a very basic question, but I can't find any mention of it elsewhere. I'm a beginning Python user.

当我使用DictReader读取数据,然后使用字典,我无法再次引用。例如,使用此代码:

When I read in data using DictReader, and then use the dictionary, I'm unable to reference it again. For example, using this code:

#!/usr/bin/python

import csv
import cgi
import cgitb
cgitb.enable()

print "<head><title>Title</title></head><body>"

f = open("blurbs.csv","rb")
blurbs = csv.DictReader(f, delimiter="\t")
for row in blurbs:
    print row
for row in blurbs:
    print row

f.close()
print "</body>"

只打印一次blurbs.csv的内容。第二个for row in blurbs:什么也没有。有什么我错过了吗?

Will only print out the contents of blurbs.csv once. The second "for row in blurbs:" does nothing. Is there something I'm missing? How can I make the dictionary into something I can reference repeatedly?

推荐答案

您只需要将文件找回到开头:

You just need to seek the file back to the start:

with open("blurbs.csv","rb") as f:
    blurbs = csv.DictReader(f, delimiter="\t")
    for row in blurbs:
        print row
    f.seek(0)
    for row in blurbs:
        print row

或者,您可以将字典生成包装到一个列表中,然后操作:

Alternatively you can wrap the dictionary generation into a list of dicts and operate on that:

with open("blurbs.csv","rb") as f:
    blurbs = list(csv.DictReader(f, delimiter="\t"))
for row in blurbs:
    print row
for row in blurbs:
    print row

这篇关于Python:如何使用DictReader两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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