查找csv文件中的列数 [英] Find number of columns in csv file

查看:321
本文介绍了查找csv文件中的列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序需要读取可能有1,2或3列的csv文件,并且需要相应地修改其行为.有没有一种简单的方法来检查列数,而无需在迭代器运行之前消耗"一行?以下代码是我能管理的最优雅的代码,但我希望在for循环开始之前运行检查:

My program needs to read csv files which may have 1,2 or 3 columns, and it needs to modify its behaviour accordingly. Is there a simple way to check the number of columns without "consuming" a row before the iterator runs? The following code is the most elegant I could manage, but I would prefer to run the check before the for loop starts:

import csv
f = 'testfile.csv'
d = '\t'

reader = csv.reader(f,delimiter=d)
for row in reader:
    if reader.line_num == 1: fields = len(row)
    if len(row) != fields:
        raise CSVError("Number of fields should be %s: %s" % (fields,str(row)))
    if fields == 1:
        pass
    elif fields == 2:
        pass
    elif fields == 3:
        pass
    else:
        raise CSVError("Too many columns in input file.")

编辑:我应该包括有关我的数据的更多信息.如果只有一个字段,则必须包含科学计数形式的名称.如果有两个字段,则第一个必须包含名称,第二个必须包含链接代码.如果有三个字段,则附加字段包含一个标志,用于指定名称当前是否有效.因此,如果任何行有1列,2列或3列,则所有列都必须相同.

I should have included more information about my data. If there is only one field, it must contain a name in scientific notation. If there are two fields, the first must contain a name, and the second a linking code. If there are three fields, the additional field contains a flag which specifies whether the name is currently valid. Therefore if any row has 1, 2 or 3 columns, all must have the same.

推荐答案

您可以使用 itertools.tee

itertools.tee(iterable [,n = 2])
从a返回n个独立的迭代器 单次迭代.

itertools.tee(iterable[, n=2])
Return n independent iterators from a single iterable.

例如

reader1, reader2 = itertools.tee(csv.reader(f, delimiter=d))
columns = len(next(reader1))
del reader1
for row in reader2:
    ...

请注意,完成对reader1的引用后,删除它很重要-否则tee必须将所有行存储在内存中,以防您再次调用next(reader1)

Note that it's important to delete the reference to reader1 when you are finished with it - otherwise tee will have to store all the rows in memory in case you ever call next(reader1) again

这篇关于查找csv文件中的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆