本文介紹了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 中的行數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!