5

Im having trouble getting the row count in a python 3 environment after migrating from 2.7. After several attempts the number of rows returned gives one. How do I get around a DeprecationWarning: 'U' mode is deprecated in python 3 ?

             input_file = open("test.csv","rU")
             reader_file = csv.reader(input_file)
             value = len(list(reader_file))

In the case of using python 3 Ive tried the following approach but Im still stuck with a 1.

             input_file = open("test.csv","rb")
             reader_file = csv.reader(input_file)
             value = len(list(reader_file))
5
  • Remove "b" from "rb". Commented Jun 4, 2019 at 0:40
  • Still gives me a 1 Commented Jun 4, 2019 at 0:43
  • 1
    Could you share an excerpt from your CSV file? Commented Jun 4, 2019 at 0:44
  • Possible duplicate of Count how many lines are in a CSV Python? Commented Jun 4, 2019 at 1:34
  • >>> len(list(csv.reader(open(r'new.csv')))) works for me. Your file only has one line. Commented Jun 4, 2019 at 2:41

2 Answers 2

16

If you are using pandas you can easily do that, without much coding stuff.

import pandas as pd

df = pd.read_csv('filename.csv')

## Fastest would be using length of index

print("Number of rows ", len(df.index))

## If you want the column and row count then

row_count, column_count = df.shape

print("Number of rows ", row_count)
print("Number of columns ", column_count)


Sign up to request clarification or add additional context in comments.

2 Comments

Much better though im still one row short
If you do read_csv and you're skipping bad lines, is there a way to get both the # of lines in the original CSV vs in the dataframe post-read?
0
input_file = open("test.csv","rb") #rb is a read-in-binary format and 
#you can't count the number of row from binary format file

with open("text.csv",'r') as f:
file = f.readlines()
print(len(file))

# Data in my text file
# a
# b
# c
# d
# e

#The output of above code is 
#5 means number of rows is 5 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.