0

I have multiple csv files for my application. I am trying to obtain number of rows and columns by reading the csv file. I have two csv files which I send through the argument file_path. First file has 5 rows and 3 columns and Second file has 5 rows and 5 columns. But using the code below I get First file with 4 rows and 3 columns and Second file with 4 rows and 5 columns. I do not understand why it skips reading one line from number of rows.
On the other hand, If I execute code for row_count first and col_count later, it gives StopIteration exception.
It may be a very simple problem but for me being a novice in Python, any help is greatly appreciated. Thanks

def read_text_file(file_path):
    with open(file_path, 'r') as f:
        reader = csv.reader(f)
        col_count = len(next(reader))
        print(col_count)       
        row_count = len(list(csv.reader(f)))
        print(row_count)
Magneto
  • 17
  • 5

3 Answers3

0

Read the CSV and store it in a list

reader = list(csv.reader(f))

This will turn the csv data into a 2D array, then you can use the len() function.

nasc
  • 289
  • 3
  • 16
0
import numpy
numpy.genfromtxt('path/to/your/csv/file.csv').shape

Should tell you the number of rows and columns as a tuple.

user171780
  • 2,243
  • 1
  • 20
  • 43
0

The problem is that a file has a notion of position. When you open it, the file is kindly positioned at the beginning. Let us go through your source:

def read_text_file(file_path):
    with open(file_path, 'r') as f:           // file is opened, pointing at first char
        reader = csv.reader(f)                // reader will use file
        col_count = len(next(reader))         // next(reader) READS FIRST ROW...
        print(col_count)                      // file is now after the first row!
        row_count = len(list(csv.reader(f)))  // read remaining rows
        print(row_count)                      // number of rows minus 1...

You should use row_count = 1 + len(list(csv.reader(f))) to add the first row that has already been read.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252