2

I want to count the total number of columns in a CSV file. Currently i am using python 2.7 and 3.4. Code works perfectly in these versions and when i try to implement the same thing in python 2.4, it is showing as next() is not defined.

Code i am using currently(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.

5
  • What about it doesn't work in Python 2.4? The csv module has been in the standard library since 2.3. Commented Sep 12, 2014 at 14:44
  • Does reader.next() work? The next builtin is new in Python 2.6. Commented Sep 12, 2014 at 14:44
  • i want to get the total number of columns in the csv file using python 2.4.. i think next() function is not defined in 2.4.. please guide me in regarding this... Commented Sep 12, 2014 at 14:46
  • i tried with readlines and split function also..it is not working Commented Sep 12, 2014 at 14:49
  • I meant reader.next(). This should have been available in 2.4. Commented Sep 12, 2014 at 14:49

2 Answers 2

3

I do not have Python 2.4 installed at the moment, so I can not really test this.

According to the documentation, the next builtin is new in Python 2.6. However, the csv.reader has a next method of it's own, and that one seems to have existed even in 2.4, so you should be able to use this.

num_cols = len(reader.next())
Sign up to request clarification or add additional context in comments.

Comments

0

assume you get a csv like this

test1,test2,test3

you can do like this

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

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.