热门标签:
Q:

发出读取csv文件

我在使用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

原网址
A:

这是因为在下面的行中-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

相似问题