3

如何使用python从csv文件中获取每3行?

import csv

with open ('data.csv','r') as infile:
    contents = csv.reader(infile, delimiter =' ')
then???

csv 文件如下所示:

aaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb
only recquired line
cccccccccccccccccccccccccc
ddddddddddddddddddddddddd
only recquired line

结果应如下所示:

only recquired line
only recquired line
4

4 回答 4

5

为避免将整个文件加载到内存中,您可以使用itertools.islice

from itertools import islice
with open ('data.csv','r') as infile:
    x = islice(infile, 2, None, 3)
    for line in x:
            print line
于 2013-11-11T02:43:22.903 回答
3
for index, line in enumerate(fileOfInterest, 1):
   if index % 3 == 0:
       doSomething

或者,您可以使用 python 的扩展切片表示法,如下所示:

for line in fileOfInterest[2::3]
   doSomething

但是,1_CR 的答案是我会选择的答案!

于 2013-11-11T02:37:54.917 回答
2
with open('test.csv') as hf:
    print [line for line in list(hf)[2::3]]
于 2013-11-11T02:51:09.510 回答
1

使用扩展切片符号

for i in contents.splitlines(True)[2::3]:
    print (i)
于 2013-11-11T02:41:33.453 回答