Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 660
Czed Avatar asked Oct 05 '11 12:10

Czed


2 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()
like image 188
Ofir Avatar answered Nov 11 '22 17:11

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
like image 27
Petr Viktorin Avatar answered Nov 11 '22 18:11

Petr Viktorin