我在使用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上的云中运行
答案 0 :(得分:4)
这是因为在以下行 - 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 r