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 n
numline = len(file_read.readlines())
row_count = sum(1 for line in open(filename))
worked for me.
Note : sum(1 for line in csv.reader(filename))
seems to calculate the length of first line
when you instantiate a csv.reader object and you iter the whole file then you can access an instance variable called line_num providing the row count:
import csv
with open('csv_path_file') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
pass
print(csv_reader.line_num)
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.
import pandas as pd
data = pd.read_csv('data.csv')
totalInstances=len(data)
try
data = pd.read_csv("data.csv")
data.shape
and in the output you can see something like (aa,bb) where aa is the # of rows