忽略/跳过带过滤器的第一行csv

时间:2016-05-23 18:30:00

标签: python csv

是否可以使用filter忽略或跳过CSV文件中的第一行?

filtered = filter(lambda p: celery == p[7],reader)
csv.writer(open(filename, 'w',newline=''), delimiter=',').writerows(filtered)

我试图仅读取和过滤包含单词celery的第7行,但由于过滤器一直在读取标题stuff,因此它会弄乱其下的行。

                                                          Stuff                                                                                                   
Apple Pear Orange Cracker Honey Cheese Grape Bread Tomato Celery Lettuce Carrot
Apple Pear Orange Cracker Honey Cheese Grape Bread Tomato Celery Lettuce Carrot
Apple Pear Orange Cracker Honey Cheese Grape Bread Tomato Celery Lettuce Carrot

我认为因为它无法找到celery它只是切断了它下面的界线?

ge Cracker Honey Cheese Grape Bread Tomato Celery Lettuce Carrot
Apple Pear Orange Cracker Honey Cheese Grape Bread Tomato Celery Lettuce Carrot
Apple Pear Orange Cracker Honey Cheese Grape Bread Tomato Celery Lettuce Carrot

1 个答案:

答案 0 :(得分:1)

在构建filtered之前添加next

  

通过调用next()方法从迭代器中检索下一个项目。如果给定default,则在迭代器耗尽时返回,否则引发StopIteration。

示例:

next(reader, None) # skips a line - default set to None
filtered = filter(lambda p: celery == p[7],reader)