问题
I am having trouble reading a saved csv with python:
import csv
with open('blah.csv','rb') as csvfile:
data = csv.reader( csvfile )
row_count = sum(1 for row in data)
print row_count
r = 1
for row in data:
print r
My issue is that although python seems to recognise the file and recognise that row_count = 9 (and prints this) it doesn't print r for each row in the later loop.
This code runs correctly on my computer, but not in the cloud on www.pythonanywhere.com
回答1:
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
来源:https://stackoverflow.com/questions/31367594/issue-reading-csv-file