問題描述
我有一個(gè) csv DictReader 對象(使用 Python 3.1),但我想知道閱讀器在迭代之前包含的行數(shù)/行數(shù).如下所示...
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))
我知道我可以通過遍歷閱讀器來獲得總數(shù),但是我無法運(yùn)行for"循環(huán).我可以遍歷閱讀器的副本,但我找不到如何復(fù)制迭代器.
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 獲取計(jì)數(shù).
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))
這篇關(guān)于csv.DictReader 中的行數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!