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))
BKCapri
  • 548
  • 2
  • 8
  • 21

2 Answers2

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)


Vim
  • 578
  • 5
  • 16
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 
DYZ
  • 55,249
  • 10
  • 64
  • 93