To Count the number of columns in a CSV file using

2019-08-03 19:26发布

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.

2条回答
爷、活的狠高调
2楼-- · 2019-08-03 20:06

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())
查看更多
可以哭但决不认输i
3楼-- · 2019-08-03 20:10

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)]
查看更多
登录 后发表回答