python计算学生总分csv,计算CSV Python中有多少条记录?

这篇博客介绍了如何在Python的Django框架中读取CSV文件,并计算文件的总行数。作者通过使用`csv.reader`来迭代文件,但遇到了获取总行数的问题。解决方案是利用生成器表达式和`sum()`函数来计数,避免将整个文件加载到内存中。如果已经读取了部分行,需要将这些行数加入到总行数中。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值