问题读取 csv 文件

Issue reading csv file

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

的云端运行不正常

那是因为在下一行 - 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