How to count the number of lines in a CSV file in Python?
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:
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.
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.