我在使用python读取已保存的csv时遇到问题:
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我的问题是虽然python似乎识别文件并识别出row_count = 9(并打印出来),但它不会为后一循环中的每一行打印r。
此代码在我的计算机上正常运行,但不在www.pythonanywhere.com上的云中运行
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 rMy 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
最满意答案
这是因为在以下行中 - row_count = sum(1 for row in data) - 您已经读完了文件并且它已经到了结尾。 所以,当你再次尝试做 -
for row in data: print r它不起作用,因为data文件在最后。
您可以尝试的许多事情之一是再次重新打开文件以从头开始读取它。
示例 -
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虽然您也可以对行进行计数并将行打印成单个循环,如 -
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你可以做的另一件事是 -
csvfile.seek(0) #to make the file point to the start.示例 -
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 rThat 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 rIt 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 rThough 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_countAnother 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更多推荐
发布评论