Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only the required lines from a csv file using python

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
like image 913
2964502 Avatar asked Feb 27 '26 09:02

2964502


1 Answers

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
like image 183
iruvar Avatar answered Mar 01 '26 23:03

iruvar