Skip to content
Related Articles

Related Articles

Improve Article

How to count the number of lines in a CSV file in Python?

  • Difficulty Level : Basic
  • Last Updated : 24 Jan, 2021

CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

In this article, we are going to discuss various approaches to count the number of lines in a CSV file using Python.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

We are going to use the below dataset to perform all operations:


# import module
import pandas as pd
# read the csv file
results = pd.read_csv('Data.csv')
# display dataset


To count the number of lines/rows present in a CSV file, we have two different types of methods:

  • Using len() function.
  • Using a counter.

Using len() function

Under this method, we need to read the CSV file using pandas library and then use the len() function with the imported CSV file, which will return an int value of a number of lines/rows present in the CSV file.


# import module
import pandas as pd
# read CSV file
results = pd.read_csv('Data.csv')
# count no. of lines
print("Number of lines present:-"


Using a counter

Under this approach, we will be initializing an integer rowcount to -1 (not 0 as iteration will start from the heading and not the first row)at the beginning and iterate through the whole file and incrementing the rowcount by one. And in the end, we will be printing the rowcount value.


#Setting initial value of the counter to zero
rowcount  = 0
#iterating through the whole file
for row in open("Data.csv"):
  rowcount+= 1
 #printing the result
print("Number of lines present:-", rowcount)


My Personal Notes arrow_drop_up
Recommended Articles
Page :