python – 问题阅读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上的云中运行

最佳答案
这是因为在下面的行中 – row_count = sum(数据中的行为1) – 您已经读完了文件并且它已经到了结尾.所以,当你再次尝试做 –

for row in data:
    print r

它不起作用,因为数据文件在最后.

您可以尝试的许多事情之一是再次重新打开文件以从头开始读取它.

示例 –

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

转载注明原文:python – 问题阅读csv文件 - 代码日志