计算CSV Python中有多少条记录? [英] Count how many records are in a CSV Python?

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

问题描述

我正在使用python(Django框架)读取CSV文件。如您所见,我仅从该CSV中提取了2行。我一直在尝试将CS​​V的总行数存储在变量中。

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.

如何获取总行数?

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

I尝试过:

len(fileObject)
fileObject.length


推荐答案

您需要计算行数:

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

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

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

如果您已经读了2行作为开始,那么您需要将这2行添加到总计中;已读取的行不计在内。

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天全站免登陆