Number of lines in csv.DictReader(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))
我知道我可以通过遍历阅读器来获得总数,但是我无法运行for"循环.我可以遍历阅读器的副本,但我找不到如何复制迭代器.
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.
任何帮助将不胜感激.
艾伦
推荐答案
rows = list(myreader)
totalrows = len(rows)
for i, row in enumerate(rows):
print("Row %d/%d" % (i+1, totalrows))
这篇关于csv.DictReader 中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:csv.DictReader 中的行数


- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 沿轴计算直方图 2022-01-01