计算CSV Python中有多少行? [英] Count how many lines are in a 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)
/ pre>
fileObject.length
解决方案您需要计算行数:
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屋!