Issue reading csv file

主宰稳场 提交于 2019-12-05 17:58:55

That is because in the following line - row_count = sum(1 for row in data) - you have already read through the file and it has reached its end. So when you again try to do -

for row in data:
    print r

It would not work, because data file is at the end.

One of the many things you can try is re-openning the file again to read it from start.

Example -

import csv
with open('blah.csv','rb') as csvfile:
    data = csv.reader( csvfile )
    row_count = sum(1 for row in data)
    print row_count

with open('blah.csv','rb') as csvfile:
    data = csv.reader( csvfile )
    r = 1
    for row in data:
        print r

Though you can also make both counting of lines and printing the line into a single loop like -

import csv
with open('blah.csv','rb') as csvfile:
    data = csv.reader( csvfile )
    row_count = 0
    for row in data
        row_count += 1
        print row
    print row_count

Another thing you can do is -

csvfile.seek(0) #to make the file point to the start.

Example -

import csv
with open('blah.csv','rb') as csvfile:
    data = csv.reader( csvfile )
    row_count = sum(1 for row in data)
    print row_count
    csvfile.seek(0)
    r = 1
    for row in data:
        print r
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!