使用python从csv文件中仅获取所需的行

时间:2013-11-11 02:33:11

标签: python csv python-3.x

如何使用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 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

for index, line in enumerate(fileOfInterest, 1):
   if index % 3 == 0:
       doSomething

或者,您可以使用python的extended slice表示法,如下所示:

for line in fileOfInterest[2::3]
   doSomething

然而,1_CR的回答是我要去的那个!

答案 2 :(得分:2)

with open('test.csv') as hf:
    print [line for line in list(hf)[2::3]]

答案 3 :(得分:1)

使用extended slice notation

for i in contents.splitlines(True)[2::3]:
    print (i)