简体   繁体   English

如何在CSV文件上每10行进行迭代

[英]How to iterate every 10 lines on CSV file

with open(example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

    for row in readCSV:
        Do something.

I need to skip every 10 lines in for loop, but doing readCSV[::10] won't work. 我需要跳过for循环中的每10行,但是执行readCSV [:: 10]无效。

with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for i, row in enumerate(readCSV):
        if i % 10 == 0:
            # do stuff with every 10th row

This boils down to iterating over every 10 th element from a generator, which can be done with itertools.islice : 这可以归结为对生成器的 10 元素进行迭代,可以使用itertools.islice完成:

import itertools
import csv

with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

    for row in itertools.islice(readCSV, None, None, 10):
        # Do something.

This does the equivalent of slicing a list (as in list[::10] ) on a generator. 这等效于在生成器上切片列表(如list[::10] )。

Keep track of the index with an iterator 使用迭代器跟踪索引

with open(example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    i = 0
    for row in readCSV:
        if i%10 = 0:
            continue
        Do something.
        i += 1

You could add this to 您可以将其添加到

count = 0
for line in f:
    count+=1
    if count % 10 == 0: 
        print line

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM