发出读取csv文件 [英] Issue reading csv file
问题描述
我无法使用python阅读已保存的csv:
import csv
with open('blah.csv','rb')as csvfile:
data = csv.reader(csvfile)
row_count = sum(数据中的行为1)
print row_count
r = 1
数据中的行:
print r
$ b $我的问题是,虽然python似乎识别该文件,并认识到row_count = 9(并打印此),它不打印r在后面的循环中的每一行。
此代码在我的计算机上正常运行,但不在www.pythonanywhere.com上的云中
这是因为在下面的行 - row_count = sum(数据中的行为1)
- 您已经读过文件,并且已经到了结束。所以当你再次尝试做 -
对于数据行:
print r
它不会工作,因为 data
p>
您可以尝试的许多方法之一是重新打开该文件以从头开始读取。
示例 -
import csv
with open('blah.csv','rb')as csvfile:
data = csv.reader(csvfile)
row_count = sum(数据中的行为1)
print row_count
with open('blah.csv','rb') as csvfile:
data = csv.reader(csvfile)
r = 1
对于数据行:
print r
虽然您也可以同时计算行数并将行打印到一个循环中,如 -
import csv
with open('blah.csv','rb')as csvfile:
data = csv.reader(csvfile)
row_count = 0
数据行中的行
row_count + = 1
打印行
打印row_count
b $ b
你可以做的另一件事是 -
csvfile.seek(0)#使文件指向开始。
示例 -
import csv
with open('blah.csv','rb')as csvfile:
data = csv.reader(csvfile)
row_count = sum在数据中)
print row_count
csvfile.seek(0)
r = 1
对于数据行:
print r
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
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
这篇关于发出读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!