Python Program to read a CSV file and display the number of rows in it
In this article, we will be solving an interesting and a basic question based on CSV file. According to the question we have to read a CSV file and display the number of rows in it.
If you like the article content, then share it in your coding groups so that more people can take advantage of the content. So, without wasting any time let's solve this question.
Question - Write a Python Program to read a CSV file and display the number of rows in it
Logic and Explanation
Question - Write a Python Program to read a CSV file and display the number of rows in it
Python Program to read a CSV file and display the number of rows in it - Suppose we are given a CSV file "crickter.csv" and we have to read this file and find out number of rows present in it.
Now, to read CSV file we have to first import the csv module.
import csv
Now, we will open the csv file in read mode.
with open("crickter.csv","r") as f:
Thereafter we will create a reader object to read the cricketer.csv file. Here, we also define a variable count with initial value as 0 to count the number of rows.
f_reader = csv.reader(f)
count = 0
Now, final step is to iterate through f_reader and then add one to count variable in each run of the loop. If there are let's say 8 rows, then loop will execute 8 times and 1 will be added to count variable 8 times so the final value of count variable will be 8 which is equal to the number of rows.
for row in f_reader:
count += 1
I hope this part is clear to you. Here's the complete source code for Python Program to read a CSV file and display the number of rows in it.
import csv
with open("crickter.csv","r") as f:
f_reader = csv.reader(f)
count = 0
for row in f_reader:
count += 1
print("Number of rows = ", count)
Output:-
Number of rows = 6
As there are 6 rows in the file cricketer.csv, our output is 6. You can see the screenshot of the CSV file below.
So, I hope you liked the article and you would have found the content of the article useful and helpful for you. Share this article in your coding communities so that more people can take advantage of the content. Also, In case of any doubt feel free to ask in the comments below.
Enjoy Coding!!!
Also Read :-
Extract Phone Number Details Using Python
Post a Comment
For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.