Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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.

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

Python3




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


Output:

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.

Python3




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


Output:

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.

Python3




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


Output:



Last Updated : 24 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads