To count the number of columns in a CSV file using python 2.4

I want to count the total number of columns in a CSV file. I am currently using python 2.7 and 3.4. The code works fine in these versions and when I try to implement the same thing in python 2.4 it shows the following () is undefined.

The code I'm currently using (2.7 and 3.4)

f = open(sys.argv[1],'r')

reader = csv.reader(f,delimiter=d)

num_cols = len(next(reader)) # Read first line and count columns


My strong need is to implement the same in Python 2.4 . Any help would be greatly appreciated.


source to share

2 answers

I don't have Python 2.4 installed, so I can't test it.

According to the documentation, next

builtin is new in Python 2.6
. It does csv.reader

have next

a method of its own
, however, and it seems to exist even in 2.4, so you should be able to use that.

num_cols = len(




Let's say you get a csv like this

test1, test2, test3

You can do it

file = open("test.csv","r")
reader = csv.reader(file)
lenCol = len(next(reader))
A = ["A"+str(i) for i in range(1,lenCol+1)]




All Articles