24
votes

I am probably making a stupid mistake, but I can't find where it is. I want to count the number of lines in my csv file. I wrote this, and obviously isn't working: I have row_count = 0 while it should be 400. Cheers.

f = open(adresse,"r")
reader = csv.reader(f,delimiter = ",")
data = [l for l in reader]
row_count = sum(1 for row in reader)

print row_count
5
The reason this happens is because the reader has "emptied" itself by creating the data list. The reader object provides a one-time for-loop, once you've worked through it, it's gone. That's why the row_count is being read as 0: there's nothing left in the reader at that point. - Erdős-Bacon

5 Answers

40
votes
with open(adresse,"r") as f:
    reader = csv.reader(f,delimiter = ",")
    data = list(reader)
    row_count = len(data)

You are trying to read the file twice, when the file pointer has already reached the end of file after saving the data list.

7
votes

First you have to open the file with open

input_file = open("nameOfFile.csv","r+")

Then use the csv.reader for open the csv

reader_file = csv.reader(input_file)

At the last, you can take the number of row with the instruction 'len'

value = len(list(reader_file))

The total code is this:

input_file = open("nameOfFile.csv","r+")
reader_file = csv.reader(input_file)
value = len(list(reader_file))

Remember that if you want to reuse the csv file, you have to make a input_file.fseek(0), because when you use a list for the reader_file, it reads all file, and the pointer in the file change its position

2
votes

If you are working with python3 and have pandas library installed you can go with

import pandas as pd

results = pd.read_csv('f.csv')

print(len(results))
0
votes
# with built in libraries
opened_file = open('f.csv')
from csv import reader

read_file = reader(opened_file)
apps_data = list(read_file)

rowcount = len(apps_data) #which incudes header row

print("Total rows incuding header: " + str(rowcount))
-5
votes

Simply Open the csv file in Notepad++. It shows the total row count in a jiffy. :) Or in cmd prompt , Provide file path and key in the command find \c \v "some meaningless string" Filename.csv