3

How to get every 3rd lines from a csv file using python?

import csv

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

The csv file looks like:

aaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb
only recquired line
cccccccccccccccccccccccccc
ddddddddddddddddddddddddd
only recquired line

The result should look like:

only recquired line
only recquired line
1
  • Nah, please see my answer. Commented Nov 11, 2013 at 2:48

4 Answers 4

5

To avoid loading the entire file into memory, you could use 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
Sign up to request clarification or add additional context in comments.

3 Comments

Interesting, I've never seen that before. Why is the second parameter (start) a 2?
@SteveP. since the OP needs every third line, the start is set to 2(index of the third line from the file)
+1 Ah, for some reason, I assumed that it was every third line, but starting at the first line...
3
for index, line in enumerate(fileOfInterest, 1):
   if index % 3 == 0:
       doSomething

Alternatively, you can use python's extended slice notation as in:

for line in fileOfInterest[2::3]
   doSomething

However, 1_CR's answer is the one I would go with!

Comments

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

Comments

1

Using the extended slice notation:

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

3 Comments

if you really had to split on newline you may as well use splitlines passing in keepends=True
Nice idea. I'll add that.
it should be contents.splitlines(True)[2::3]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.