计算CSV Python中有多少行? [英] Count how many lines are in a CSV Python?

查看:275
本文介绍了计算CSV Python中有多少行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python(Django Framework)来读取一个CSV文件。我可以看到,我从这个CSV中拉出两行。我一直在努力做的就是存储一个变量CSV的总行数。



如何获取总行数? / strong>

  file = object.myfilePath 
fileObject = csv.reader(file)
for i在范围(2):
data.append(fileObject.next())

尝试:

  len(fileObject)
fileObject.length
/ pre>

解决方案

您需要计算行数:

  row_count = sum(1对于fileObject中的行)#fileObject是您的csv.reader 

使用生成器表达式使用 sum()可以提供有效的计数器,避免将整个文件存储在内存中。



如果您已经阅读了2行,那么您需要将这2行添加到您的总数中;已经读取的行未被计入。


I'm using python (Django Framework) to read a CSV file. I pull just 2 lines out of this CSV as you can see. What I have been trying to do is store in a variable the total number of rows the CSV also.

How can I get the total number of rows?

file = object.myfilePath
fileObject = csv.reader(file)
for i in range(2):
    data.append(fileObject.next()) 

I have tried:

len(fileObject)
fileObject.length

解决方案

You need to count the number of rows:

row_count = sum(1 for row in fileObject)  # fileObject is your csv.reader

Using sum() with a generator expression makes for an efficient counter, avoiding storing the whole file in memory.

If you already read 2 rows to start with, then you need to add those 2 rows to your total; rows that have already been read are not being counted.

这篇关于计算CSV Python中有多少行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆