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

I would like to print (stdout) the first two lines of the 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 prints the first two columns.

Any suggestions?

+4
source share
2 answers

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

Since you want to print the entire line, you can simply print it and, in addition, read only 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() 
+13
source

Typically, you can restrict iterators with the itertools.islice function:

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

Or by creatively using zip() :

 for line_number, row in zip(range(2), csvReader1): print row 
+5
source

All Articles