Print the first two rows of a csv file to a standard output

Question:

I would like to print (stdout) the first two lines of a csv file:

#!/usr/bin/env python
import csv
afile = open('<directory>/*.csv', 'r+')
csvReader1 = csv.reader(afile)
for row in csvReader1:
    print row[0]
    print row[1]

however, my output using this code print the first two columns.

Any suggestions?

Asked By: Czed

||

Answers:

You want to print a row, but your code asks to print the first and second members of each row

Since you want to print the whole row – you can simply print it, and in addition, only read the first two

#!/usr/bin/env python
import csv
afile = open('<directory>/*.csv', 'r+')
csvReader1 = csv.reader(afile)
for i in range(2):
    print csvReader1.next()
Answered By: Ofir

Generally, you can limit iterators with the itertools.islice function:

import itertools
for row in itertools.islice(csvReader1, 2):
    print row

Or by a creative use of zip():

for line_number, row in zip(range(2), csvReader1):
    print row
Answered By: Petr Viktorin

You can use enumerate too

for i, row in enumerate(csvReader1):
    if (i > 1):
        print (row)
    else:
        break
    
Answered By: Shonubi Korede
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.