使用python 2.4计算CSV文件中的列数 [英] To Count the number of columns in a CSV file using python 2.4
问题描述
我想计算CSV文件中的总列数.目前,我正在使用python 2.7和3.4.代码在这些版本中运行完美,当我尝试在python 2.4中实现相同的功能时,它显示为next()未定义.
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.
我当前正在使用的代码(2.7和3.4)
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
我的强烈需求是在 Python 2.4 中实现相同的功能.任何帮助将不胜感激.
My strong need is to implement the same in Python 2.4 . Any help would be greatly appreciated.
推荐答案
目前我尚未安装Python 2.4,因此我无法真正对其进行测试.
I do not have Python 2.4 installed at the moment, so I can not really test this.
根据文档,内置的 next
是Python 2.6中的新增功能.但是,csv.reader
拥有自己的 next
方法,甚至在2.4中似乎也已经存在,所以您应该可以使用它.
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())
这篇关于使用python 2.4计算CSV文件中的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!