如何从 Python 中的 CSV 文件中获取总行数? [英] How to obtain the total numbers of rows from a CSV file in Python?

查看:147
本文介绍了如何从 Python 中的 CSV 文件中获取总行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python(Django 框架)读取 CSV 文件.如您所见,我只从这个 CSV 文件中提取了 2 行.我一直在尝试做的是将 CSV 的总行数也存储在一个变量中.

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()) 

我试过了:

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.

这篇关于如何从 Python 中的 CSV 文件中获取总行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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