csv.DictReader中的行数 [英] Number of lines in csv.DictReader

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

问题描述

我有一个csv DictReader对象(使用Python 3.1),但我想知道<=>之前中包含的行数/行数迭代它。如下所示......

I have a csv DictReader object (using Python 3.1), but I would like to know the number of lines/rows contained in the reader before I iterate through it. Something like as follows...

myreader = csv.DictReader(open('myFile.csv', newline=''))

totalrows = ?

rowcount = 0
for row in myreader:
    rowcount +=1
    print("Row %d/%d" % (rowcount,totalrows))

我知道我可以通过迭代读取器得到总数,但后来我无法运行'为'循环。我可以遍历阅读器的副本,但我找不到如何复制迭代器。

I know I could get the total by iterating through the reader, but then I couldn't run the 'for' loop. I could iterate through a copy of the reader, but I cannot find how to copy an iterator.

我也可以使用

totalrows = len(open('myFile.csv').readlines())

但这似乎是不必要的重新打开文件。如果可能的话,我宁愿从DictReader获得计数。

but that seems an unnecessary re-opening of the file. I would rather get the count from the DictReader if possible.

任何帮助都将不胜感激。

Any help would be appreciated.

Alan

推荐答案

rows = list(myreader)
totalrows = len(rows)
for i, row in enumerate(rows):
    print("Row %d/%d" % (i+1, totalrows))

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

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